题目地址:
https://www.luogu.com.cn/problem/P1601
题目描述
高精度加法,相当于a+b problem,不用考虑负数.
输入格式:
分两行输入。
a
,
b
≤
1
0
500
a,b \leq 10^{500}
a,b≤10500
输出格式:
输出只有一行,代表
a
+
b
a+b
a+b的值
高精度加法。以字符串的方式输入,手工模拟整数加法就可以了。注意最后要判断最高位是否有进位。代码如下:
#include <algorithm>
#include <iostream>
using namespace std;
string res;
string s1, s2;
int main() {
cin >> s1;
cin >> s2;
reverse(s1.begin(), s1.end());
reverse(s2.begin(), s2.end());
int t = 0;
for (int i = 0; i < s1.size() || i < s2.size(); i++) {
if (i < s1.size()) t += s1[i] - '0';
if (i < s2.size()) t += s2[i] - '0';
res += '0' + t % 10;
t /= 10;
}
if (t) res += '1';
reverse(res.begin(), res.end());
cout << res << endl;
}
时空复杂度 O ( max { l a , l b } ) O(\max\{l_a,l_b\}) O(max{la,lb})。