题解 | #高精度整数加法#
高精度整数加法
https://www.nowcoder.com/practice/49e772ab08994a96980f9618892e55b6
#include <iostream> #include <string> #include <stack> using namespace std; int main() { string str1, str2; cin >> str1 >> str2; stack<char> stack_1; for (auto item : str1) stack_1.push(item); stack<char> stack_2; for (auto item : str2) stack_2.push(item); int flag = 0; // 进位标志 string ans = ""; while (!stack_1.empty() || !stack_2.empty()) { int num_1 = 0, num_2 = 0; if (!stack_1.empty()) { num_1 = stack_1.top() - '0'; stack_1.pop(); } if (!stack_2.empty()) { num_2 = stack_2.top() - '0'; stack_2.pop(); } ans = to_string((num_1 + num_2 + flag) % 10) + ans; flag = (num_1 + num_2 + flag) / 10; } if (flag == 1) ans = to_string(flag) + ans; cout << ans << endl; } // 64 位输出请用 printf("%lld")