题解 | #高精度整数加法#
高精度整数加法
https://www.nowcoder.com/practice/49e772ab08994a96980f9618892e55b6
// 大数问题,用字符串来模拟加法运算,主要考虑进位情况
#include <algorithm>
#include <iostream>
#include <string>
using namespace std;
int main() {
string str1, str2;
cin >> str1 >> str2;
reverse(str1.begin(), str1.end());
reverse(str2.begin(), str2.end());
int len1 = str1.length();
int len2 = str2.length();
int carry = 0;
string ans;
int i = 0, j =0;
for(; i < len1 && j < len2; i++,j++){
int sum = (str1[i] - '0') + (str2[j] - '0') + carry ;
if( sum >= 10){
carry = 1;
ans += to_string(sum%10);
}else{
carry = 0;
ans += to_string(sum);
}
}
for(; i < len1; i++){
int sum = (str1[i] - '0') + carry ;
if( sum >= 10){
carry = 1;
ans += to_string(sum%10);
}else{
carry = 0;
ans += to_string(sum);
}
}
for(; j < len2; j++){
int sum = (str2[j] - '0') + carry ;
if( sum >= 10){
carry = 1;
ans += to_string(sum%10);
}else{
carry = 0;
ans += to_string(sum);
}
}
if(carry){
ans += to_string(carry);
}
reverse(ans.begin(), ans.end());
cout << ans << endl;
return 0;
}
// 64 位输出请用 printf("%lld")
