大数加法
1 #include <iostream> 2 3 using namespace std; 4 5 string add(string str1, string str2)//大数加法 6 { 7 string str; 8 int len1 = str1.length(); 9 int len2 = str2.length(); 10 if(len1 < len2) 11 { 12 for(int i = 1; i <= len2 - len1; i++) 13 { 14 str1 = '0' + str1; 15 } 16 } 17 else { 18 for(int i = 1; i <= len1 - len2; i++) 19 { 20 str2 = "0" + str2; 21 } 22 } 23 len1 = str1.length(); 24 int cmp = 0; 25 int ans; 26 for(int i = len1 - 1; i >= 0; i--) 27 { 28 ans = str1[i] - '0' + str2[i] - '0' + cmp; 29 cmp = ans/10; 30 ans %= 10; 31 str = char(ans + '0') + str; 32 } 33 return str; 34 } 35 36 int main() 37 { 38 string a, b; 39 while(cin >> a >> b) 40 { 41 cout << add(a,b) << endl; 42 } 43 return 0; 44 }
两个数均大于等于0