1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43
| #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());
string ans(len, '0') ;
for(int i = 0; i < a.length(); i++) ans[i] = a[i] ;
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; }
|