65,211
社区成员
发帖
与我相关
我的任务
分享
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
class BigInt { //定义大整数类
string s;
public:
BigInt(string s1) { s = s1; }
~BigInt () {}
friend BigInt operator+ (BigInt a, BigInt b); //重载操作符+
friend ostream& operator<<( ostream& o, const BigInt &a ); //重载输出操作符
};
BigInt operator+ (BigInt a, BigInt b) {
int MaxLen, MinLen,temp,i,j;
int carry = 0;
a.s.size() < b.s.size() ? MaxLen = b.s.size(),MinLen = a.s.size() : MaxLen = a.s.size(),MinLen = b.s.size();
for (i = MaxLen-1, j = MinLen - 1; i >= 0, j >= 0; i--,j--) {
temp = a.s[i] - '0' + b.s[j] -'0' + carry;
a.s[i] = temp % 10 + '0';
carry = temp/10;
}
while (carry > 0) {
temp = a.s[i] -'0' + carry;
a.s[i] = temp%10 +'0';
carry = temp/10;
i--;
}
return a;
}
ostream& operator<<( ostream& o, const BigInt &a ) {
return o << a.s << endl;
}
int main () {
BigInt a("445555555555555555555555545555");
BigInt b("1");
cout << a+b;
BigInt a1("1");
BigInt b1("445555555555555555555555545555");
cout << a1+b1; //反过来写为什么不行
}
int main () {
BigInt a("5455555555555555555555555555555");
BigInt b("66666666666666666666666666666666666666");
cout << a+b;
}
int main () {
BigInt a("5455555555555555555555555555555");
BigInt b("66666666666666666666666666666666666666");
cout << a+b;
}
a.s.size() <= b.s.size() ? (MaxLen = b.s.size(),MinLen = a.s.size(), c = b.s, d = a.s) : (MaxLen = a.s.size(),MinLen = b.s.size(), c = a.s, d = b.s);
int main () {
BigInt a("500000000000000000000000000000000000");
BigInt b("500000000000000000000000000000000000");
cout << a+b;
}
for (i = MaxLen-1, j = MinLen - 1; i >= 0, j >= 0; i--,j--) {
temp = a.s[i] - '0' + b.s[j] -'0' + carry; //第2个情况这里的 a.s[i] 和 b.s[j] 也要换过来的
a.s[i] = temp % 10 + '0';
carry = temp/10;
}
while (carry > 0) {
temp = a.s[i] -'0' + carry;
a.s[i] = temp%10 +'0';
carry = temp/10;
i--;
}
a.s.size() < b.s.size() ? (MaxLen = b.s.size(),MinLen = a.s.size(), c = b.s, d = a.s) : (MaxLen = a.s.size(),MinLen = b.s.size(), c = a.s, d = b.s);
for (i = MaxLen-1, j = MinLen - 1; i >= 0&&j >= 0; i--,j--) {
temp = c[i] - '0' + d[j] - '0' + carry;
c[i] = temp % 10 + '0';
carry = temp/10;
}
while (carry > 0) {
temp = c[i] -'0' + carry;
c[i] = temp%10 +'0';
carry = temp/10;
i--;
}
a.s = c;
return a;