题解
2025-08-26 10:09:06
发布于:浙江
5阅读
0回复
0点赞
#include <bits/stdc++.h>
using namespace std;
// 高精度加法函数
string add(const string& a, const string& b) {
vector<int> A, B, C;
int carry = 0;
// 倒序读取数字
for (int i = a.size() - 1; i >= 0; --i) A.push_back(a[i] - '0');
for (int i = b.size() - 1; i >= 0; --i) B.push_back(b[i] - '0');
// 从低位开始加
int n = max(A.size(), B.size());
for (int i = 0; i < n || carry; ++i) {
if (i < A.size()) carry += A[i];
if (i < B.size()) carry += B[i];
C.push_back(carry % 10);
carry /= 10;
}
// 构造结果字符串,去掉前导零
string res;
int idx = C.size() - 1;
while (idx >= 0 && C[idx] == 0) idx--;
if (idx < 0) return "0"; // 全部为零的情况
while (idx >= 0) res += to_string(C[idx--]);
return res;
}
int main() {
string a, b;
cin >> a >> b;
cout << add(a, b) << endl;
return 0;
}
全部评论 1
dd
1周前 来自 浙江
0
有帮助,赞一个