题解 | #高精度整数加法#
高精度整数加法
https://www.nowcoder.com/practice/49e772ab08994a96980f9618892e55b6
#include <iostream>
#include <string>
using namespace std;
int main() {
string str1, str2;
cin >> str1 >> str2;
int idx1 = str1.size() - 1, idx2 = str2.size() - 1;
int carry = 0;
string res;
// 倒序遍历,逐个相加,并转成字符串处理
while (idx1 >= 0 || idx2 >= 0) {
int num1 = 0;
int num2 = 0;
// 两个字符串都有效
if (idx1 >= 0 && idx2 >= 0) {
num1 = stoi(str1.substr(idx1, 1));
num2 = stoi(str2.substr(idx2, 1));
}
// 只有str2有效
if (idx1 < 0) {
num2 = stoi(str2.substr(idx2, 1));
}
// 只有str1有效
if (idx2 < 0) {
num1 = stoi(str1.substr(idx1, 1));
}
// 累加
int sum = num1 + num2 + carry;
// 保存进位
carry = sum / 10;
sum %= 10;
// 保存当前位置结果
res = std::to_string(sum) + res;
idx1--;
idx2--;
}
// 增加最后的进位
if (carry) {
res = std::to_string(carry) + res;
}
cout << res << endl;
}
// 64 位输出请用 printf("%lld")
