题解 | #高精度整数加法#
高精度整数加法
https://www.nowcoder.com/practice/49e772ab08994a96980f9618892e55b6
#include <iostream> #include <string> #include <algorithm> // 包含 std::reverse using namespace std; string add_two_string(const string& a, const string& b) { string result; // 存储最终结果 int carry = 0; // 进位标志 // 逆转字符串方便计算 string rev_a = a; string rev_b = b; reverse(rev_a.begin(), rev_a.end()); reverse(rev_b.begin(), rev_b.end()); int max_len = max(rev_a.size(), rev_b.size()); for (int i = 0; i < max_len || carry; ++i) { int digit_a = (i < rev_a.size()) ? rev_a[i] - '0' : 0; int digit_b = (i < rev_b.size()) ? rev_b[i] - '0' : 0; int sum = digit_a + digit_b + carry; carry = sum / 10; result.push_back((sum % 10) + '0'); } // 逆转结果字符串 reverse(result.begin(), result.end()); return result; } int main() { string a, b; cin >> a >> b; string result = add_two_string(a, b); cout << result << endl; return 0; }