【算法1-1】模拟与高精度—加法篇
同理参照高精度算法-减法篇,一个模板改过来的
解决跟高精度减法不同的问题:
没有前导零的存在,但是可能会出现位数增多的情况
比如:9999+9999=19998
1 if (ans[maxl + 1] > 0) 2 maxl++;
终极代码:
1 #include<iostream> 2 #include<string> 3 #include<algorithm> 4 using namespace std; 5 int arr1[200000], arr2[200000], ans[200000]; 6 string jiafa(string s1, string s2) 7 { 8 int maxl = max(s1.length(), s2.length()); 9 string ss; 10 if (s1.length() < s2.length() || (s1.length() == s2.length() && s1 < s2)) 11 { 12 return jiafa(s2, s1); 13 } 14 for (int i = 1; i <= s1.length(); i++) 15 arr1[i] = s1[s1.size() - i] - '0'; 16 for (int i = 1; i <= s2.length(); i++) 17 arr2[i] = s2[s2.size() - i] - '0'; 18 for (int i = 1; i <= maxl; i++) 19 ans[i] = arr1[i] + arr2[i]; 20 for (int i = 1; i <=maxl; i++) 21 { 22 if (ans[i]>9) 23 { 24 ans[i] -= 10; 25 ans[i + 1]++; 26 } 27 } 28 if (ans[maxl + 1] > 0) 29 maxl++; 30 for (int i = maxl; i >0; i--) 31 ss += ans[i] + '0'; 32 return ss; 33 } 34 int main() 35 { 36 string s1, s2; 37 cin >> s1 >> s2; 38 cout << jiafa(s1, s2); 39 }