內建類型 (long long ≤ 1018) 無法容納超大整數。解決方案:**字符串存儲數字,模擬人工豎式加法**,逐位相加處理進位。
str1, str2。ch - '0') 相加 + 進位 carry。sum % 10,新進位 = sum / 10。carry > 0 壓入棧。#include <iostream>
#include <string>
#include <stack>
using namespace std;
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
string str1, str2;
while (cin >> str1 >> str2) { // 支持多組輸入
stack st;
int carry = 0;
int i = str1.length() - 1;
int j = str2.length() - 1;
// 同時遍歷公共長度
while (i >= 0 && j >= 0) {
int sum = (str1[i] - '0') + (str2[j] - '0') + carry;
st.push(sum % 10);
carry = sum / 10;
--i; --j;
}
// 處理剩餘長串
while (i >= 0) {
int sum = (str1[i] - '0') + carry;
st.push(sum % 10);
carry = sum / 10;
--i;
}
while (j >= 0) {
int sum = (str2[j] - '0') + carry;
st.push(sum % 10);
carry = sum / 10;
--j;
}
// 最終進位
if (carry) st.push(carry);
// 輸出
while (!st.empty()) {
cout << st.top();
st.pop();
}
cout << '\n';
}
return 0;
}
| 環節 | 處理細節 |
|---|---|
| 字符轉數值 | ch - '0' (ASCII 連續碼),比 atoi 快且安全 |
| 進位計算 | sum / 10 (整除), sum % 10 (取模) |
| 逆序輸出 | stack 天然 LIFO,無需手動反轉字符串 |
| 前導零 | 算法天然不產生前導零 (最高位進位單獨壓棧) |
| 負數擴展 | 若需支持負數,先比較絕對值大小、符號位,轉為減法或異號加法 |
O(max(N, M)),單次遍歷。O(max(N, M)),棧存儲結果位。base=10000) 或 32 位 (base=2^32),減少循環次數 4-9 倍 (大數乘法必備)。string 或 vector 末尾,最後 reverse,省去棧開銷。