6-5 大整数求和(运算符重载) BigInt类表示不超过100位的无符号大整数。试重载>>,<<和+,以支持无符号大整数的输入、输出与求和(假设结果仍是一个不超过100位的无符号大整数)。
时间: 2024-05-28 10:08:41 浏览: 38
#include <iostream>
#include <cstring>
using namespace std;
const int MAXN = 110;
class BigInt {
private:
int num[MAXN]; // 存储每一位数字
public:
BigInt() {
memset(num, 0, sizeof(num)); // 初始化为0
}
friend istream& operator>>(istream& in, BigInt& b) {
string s;
in >> s;
int len = s.length();
for (int i = 0; i < len; i++) {
b.num[i] = s[len - i - 1] - '0'; // 逆序存储每一位数字
}
return in;
}
friend ostream& operator<<(ostream& out, BigInt& b) {
int len = MAXN - 1;
while (len > 0 && b.num[len] == 0) {
len--;
}
for (int i = len; i >= 0; i--) {
out << b.num[i];
}
return out;
}
friend BigInt operator+(BigInt& a, BigInt& b) {
BigInt c;
int carry = 0; // 进位
for (int i = 0; i < MAXN; i++) {
int sum = a.num[i] + b.num[i] + carry;
c.num[i] = sum % 10;
carry = sum / 10;
}
return c;
}
};
int main() {
BigInt a, b, c;
cin >> a >> b;
c = a + b;
cout << c << endl;
return 0;
}
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)