AC代码如下
#include <iostream>
#include <string>
using namespace std;
// 大数相乘
string bigIntegerPlus(string res, string plusN) {
string ret;
if (res.length()< plusN.length()) {
string tmp = res;
res = plusN;
plusN = tmp;
}
int len1 = res.length(), len2 = plusN.length();
for (int i = len2-1; i>=0; --i ) {
string tmp(len1, '0'); // 存放相乘的中间结果
int goBit =0;
for (int j= len1-1; j >=0; --j) {
int mid = (res[j] -'0') * (plusN[i] -'0') + goBit;
tmp[j] = mid%10 + '0';
goBit = mid /10;
}
if (goBit != 0)
tmp.insert(0, string(1,goBit +'0'));
for (int m=0; m< len2 -1-i; ++m)
tmp.push_back('0'); // 补位
// 相乘后就相加 大数相加
if (i == len2-1)
ret = tmp;
else {
int goBit2 =0;
string s(tmp.length() - ret.length() ,'0');
ret = s + ret;
for (int m = tmp.length()-1; m>=0; --m) {
int mid = (tmp[m] -'0')+(ret[m] - '0') + goBit2;
ret[m] = mid %10 +'0';
goBit2 = mid/ 10;
}
if (goBit2 != 0)
ret.insert(0, string(1,goBit +'0'));
}
}
// 去掉前导0
while (ret.length() >1 && ret[0] == '0')
ret.erase(0,1);
return ret;
}
int main(int argc, char** argv) {
string res, plusN;
while (cin>> res>> plusN) {
cout<< bigIntegerPlus(res, plusN)<< endl;
}
return 0;
}
总的思路比较简单, 就是模拟手算。 用较短(或相等)长度的数的每一位与较长数一一相乘。要注意的是,相乘所得结果需要补0的细节 。然后就是单纯的大数相加。
用c++的string来做 写起来挺顺手的。