string实现高精度加法,通过反转字符串使得加法过程更简单且不用考虑前导零。
#include <iostream>
using namespace std;
string rev(string a){
string res;
for(char c:a) res = c + res;
return res;
}
string remove_pre0(string a){
int i = a.size() - 1;
while(a.size() >= 1){
if(a[i] == '0') a = a.substr(0, a.size()-1), i = a.size() - 1;
else break;
}
if(a == "") return "0";
return a;
}
string add(string a, string b){
int len = min(a.size(), b.size());
string res;
int carry = 0;
int i = 0;
for(i = 0; i < len; i++){
int sum = a[i] - '0' + b[i] - '0' + carry;
carry = sum / 10;
sum %= 10;
res += to_string(sum);
}
while(i < a.size()){
int sum = a[i++] - '0' + carry;
carry = sum / 10;
sum %= 10;
res += to_string(sum);
}
while(i < b.size()){
int sum = b[i++] - '0' + carry;
carry = sum / 10;
sum %= 10;
res += to_string(sum);
}
if(carry) res += to_string(carry);
remove_pre0(res);
return res;
}
int main(){
string a, b;
cin>>a>>b;
cout << rev(add(rev(a), rev(b)));
}