#include<bits/stdc++.h>
using namespace std;
string add(string a, string b){
a = a.substr(a.find_first_not_of('0'));
b = b.substr(b.find_first_not_of('0'));
long long lenA = a.length();
long long lenB = b.length();
long long len = max(lenA, lenB) + 10;
// 翻转,便于从低位逐步求和
reverse(a.begin(), a.end()) ;
reverse(b.begin(), b.end());
// 初始化答案为len长,全部为字符0
string ans(len, '0') ;
// 把a拷贝到ans中
for(int i = 0; i < a.length(); i++)
ans[i] = a[i] ;
// tmp 是上一位相加后的进位
int tmp = 0;
for(int i = 0; i < len; i ++) {
if(i < b.length())
tmp += (ans[i] - '0') + (b[i] - '0');
else
tmp += (ans[i] - '0');
ans[i] = tmp % 10 + '0';
tmp /= 10; // 留给计算下一位用 (这里利用了强制类型转换)
}
reverse(ans.begin(), ans.end());
return ans.substr(ans.find_first_not_of('0'));
}
int main(){
string a = "9999999999";
string b = "1111111111";
cout << add(a, b) << endl;
return 0;
}
转载于:https://www.cnblogs.com/ishero/p/11136362.html