大數加法模板
阿新 • • 發佈:2017-08-15
cin str 大數加法 oid blog name main clas namespace
計算 a + b
1 #include <iostream> 2 #include <algorithm> 3 using namespace std; 4 5 string sol; 6 7 void solve(string a, string b){ 8 int j = b.size() - 1, i = a.size() - 1, cnt = 0; 9 for(; i >= 0 && j >= 0; i--, j--){ 10 int x = a[i] - ‘0‘; 11 inty = b[j] - ‘0‘; 12 sol += (char)((x + y + cnt) % 10 + ‘0‘); 13 cnt = (x + y + cnt) / 10; 14 } 15 while(i >= 0){ 16 int x = a[i--] - ‘0‘; 17 sol += (char)((x + cnt) % 10 + ‘0‘); 18 cnt = (x + cnt) / 10; 19 } 20 while(j >= 0){ 21 int y = b[j--] - ‘0‘; 22 sol += (char)((y + cnt) % 10 + ‘0‘); 23 cnt = (y + cnt) / 10; 24 } 25 if(cnt) sol += ‘1‘; 26 reverse(sol.begin(), sol.end()); 27 } 28 29 int main(void){ 30 string a, b; 31 cin >> a >> b; 32 solve(a, b); 33 cout << sol << endl; 34 return0; 35 }
大數加法模板