未完待续的C++大数类BigInteger

看着JAVA诱人的大数类在ACM中很好用,可是我不会JAVA,感觉为了大数类去学习JAVA太麻烦了,不如写个C++的大数类,目前还未完善,只有部分功能的雏形,因为现在知识有限,即使拿着C++ Primer Plus和刘汝佳的白书各种翻,也才写了这一点,不过目测除了前导零没有什么bug了,刚才拿这个代码A了个题。。然后我打算慢慢完善它。。。

 1 #include <iostream>

 2 #include <cstring>

 3 using namespace std;

 4 const int MAXLENTH = 10000;

 5 class BigInteger

 6 {

 7     private:

 8     char s[MAXLENTH+10];

 9     int len;

10     public:

11     void init(){memset(s, 0, sizeof(s)); len = 1;}

12     BigInteger(){init();}

13     friend istream& operator>> (istream &in, BigInteger &x);

14     friend ostream& operator<< (ostream &out, BigInteger &x);

15     BigInteger operator= (char *num);

16     BigInteger operator+ (BigInteger &y);

17     BigInteger operator+= (BigInteger &y);

18 };

19 

20 istream& operator>> (istream &in, BigInteger &x)

21 {

22     x.init();

23     char str[MAXLENTH];

24     in >> str;

25     x = str;

26     return in;

27 }

28 

29 ostream& operator<< (ostream &out, BigInteger &x)

30 {

31     char ans[MAXLENTH];

32     for(int i = 0; i < x.len; i++)

33         ans[i] = x.s[x.len-i-1] + '0';

34     ans[x.len] = '\0';

35     out << ans;

36     return out;

37 }

38 

39 BigInteger BigInteger::operator= (char *num)

40 {

41     len = strlen(num);

42     for(int i = 0; i < len; i++)

43         s[i] = num[len-i-1] - '0';

44     return *this;

45 }

46 

47 BigInteger BigInteger::operator+ (BigInteger &y)

48 {

49     BigInteger z;

50     for(int i = 0, c = 0; i <= MAXLENTH; i++)

51     {

52         int sum = s[i] + y.s[i] + c;

53         z.s[i] = sum % 10;

54         c = sum / 10;

55     }

56     int j = MAXLENTH;

57     for( ; j > 0; j--)

58         if(z.s[j])break;

59     z.len = j+1;

60     return z;

61 }

62 

63 BigInteger BigInteger::operator+= (BigInteger &y)

64 {

65     *this = *this + y;

66     return *this;

67 }

68 

69 int main()

70 {

71     BigInteger a, b, c;

72     while(cin >> a >> b)

73     {

74         c = a + b;

75         cout << c << endl;

76     }

77     return 0;

78 }

 

你可能感兴趣的:(BIgInteger)