image.png

    1. #include <iostream>
    2. #include <cstring>
    3. #include <cstdlib>
    4. #include <cstdio>
    5. using namespace std;
    6. const int MAX = 110;
    7. class CHugeInt
    8. {
    9. public:
    10. int arr[MAX]{0};
    11. int len;
    12. CHugeInt(int n)
    13. {
    14. arr[0] = n;
    15. len = 1;
    16. }
    17. CHugeInt(const char *s)
    18. {
    19. len = strlen(s) / 9 + 1; // 一个int元素最多存9位,因为int是10位,防止溢出
    20. const char *p = s; // 指向第一个数字
    21. int i = len;
    22. // 把高位数存在数组的后面,如果出现高位进位,方便处理
    23. while (i--)
    24. {
    25. for (int j = 0; j < 9 && *p != '\0'; ++j, ++p)
    26. {
    27. arr[i] = arr[i] * 10 + (*p - '0'); // 逐位将字符串读入int数组
    28. }
    29. }
    30. }
    31. CHugeInt(const CHugeInt &hi)
    32. {
    33. memcpy(arr, hi.arr, hi.len * sizeof(int));
    34. len = hi.len;
    35. }
    36. CHugeInt operator+(const CHugeInt &hi) // 把右边的加到左边上
    37. {
    38. int i = 0;
    39. CHugeInt tmp(*this);
    40. int c = 0; // 低位进位
    41. do
    42. {
    43. int sum = tmp.arr[i] + hi.arr[i] + c;
    44. c = sum / 1000000000;
    45. tmp.arr[i] = sum % 1000000000;
    46. ++i;
    47. } while ((i <= hi.len) && (i <= tmp.len));
    48. return tmp;
    49. }
    50. void operator+=(int n)
    51. {
    52. int sum = arr[0] + n;
    53. int c = sum / 1000000000;
    54. arr[1] += c;
    55. arr[0] = sum % 1000000000;
    56. }
    57. CHugeInt &operator++()
    58. {
    59. int sum = arr[0] + 1;
    60. if (sum == 1000000000)
    61. {
    62. arr[0] = 0;
    63. arr[1] += 1;
    64. }
    65. else
    66. {
    67. arr[0] = sum;
    68. }
    69. return *this;
    70. }
    71. CHugeInt operator++(int)
    72. {
    73. CHugeInt tmp(*this);
    74. int sum = arr[0] + 1;
    75. if (sum == 1000000000)
    76. {
    77. arr[0] = 0;
    78. arr[1] += 1;
    79. }
    80. else
    81. {
    82. arr[0] = sum;
    83. }
    84. return tmp;
    85. }
    86. friend ostream &operator<<(ostream &os, const CHugeInt &hi)
    87. {
    88. int i = hi.len;
    89. while (i--)
    90. {
    91. os << hi.arr[i];
    92. }
    93. return os;
    94. }
    95. };
    96. CHugeInt operator+(int n, const CHugeInt &hi)
    97. {
    98. CHugeInt tmp(hi);
    99. int sum = tmp.arr[0] + n;
    100. int c = sum / 1000000000;
    101. tmp.arr[1] += c;
    102. tmp.arr[0] = sum % 1000000000;
    103. return tmp;
    104. }
    105. int main()
    106. {
    107. char s[210];
    108. int n;
    109. while (cin >> s >> n)
    110. {
    111. CHugeInt a(s);
    112. CHugeInt b(n);
    113. cout << a + b << endl;
    114. cout << n + a << endl;
    115. cout << a + n << endl;
    116. b += n;
    117. cout << ++b << endl;
    118. cout << b++ << endl;
    119. cout << b << endl;
    120. }
    121. return 0;
    122. }
    • 考察各种运算符的重载,“+”、自增运算符、流输出运算符。需要注意以下几点:
      1. memcpy()函数最后一个参数是拷贝的字节数,所以一般用n * sizeof()作为该参数的实参
      2. 前置“++”要返回自己引用,后置“++”别忘了自己加完了,返回加之前的自己的临时对象
      3. “+=”运算符也是需要重载的