輸入兩個不超過 100 位的大整數,輸出它們的乘積。樣例:1234567 123 → 151851741。OJ 提交需去除調試輸出。
num1、num2num2 每一位 (從低位到高位)num1 每位相乘 + 進位,結果存入臨時數組 tempRestempRes 與總結果 result 對齊相加 (每輪左偏移一位),處理進位// 計算 num1 × num2[j] 存入 tempRes
for (i = num1Len-1; i >= 0; i--) {
res = Int(num1[i]) * Int(num2[j]) + carry;
tempRes[tempResLen--] = Char(res % 10);
carry = res / 10;
}
tempRes[tempResLen] = Char(carry); // 最高位進位
// tempRes 與 result 累加 (右對齊,每輪左偏移)
for (k = resultLen-offset; k > resultLen-offset-num1Len; k--) {
res = Int(result[k]) + Int(tempRes[tempResLen--]) + carry;
result[k] = Char(res % 10);
carry = res / 10;
}
result[k] += Int(tempRes[tempResLen] + carry);
宏定義技巧:#define Int(X) (X-'0')、#define Char(X) (X+'0') 實現字符/數字快速轉換。
乘法本質是各位乘積按權重累加。可先忽略進位,將所有 num1[i] × num2[j] 直接累加到 result[i+j] 對應位置,最後從低位向高位統一處理進位。
result 類型必須為 int (而非 char),因單位最大累加值 100×9×9=8100 超出 char 范圍result[i+j+2] += Int(num1[i]) * Int(num2[j]) (前兩位保留長度與最終進位)result[i-1] += result[i]/10; result[i] %= 10// 免進位累加
for (j = 0; j < num2Len; j++)
for (i = 0; i < num1Len; i++)
result[i+j+2] += Int(num1[i]) * Int(num2[j]);
// 統一進位
for (i = resultLen; i > 1; i--) {
result[i-1] += result[i] / 10;
result[i] %= 10;
}
| 維度 | 模擬筆算法 | 免進位累加法 |
|---|---|---|
| 思路直觀度 | 高,貼近人工計算 | 中,需理解位權重累加本質 |
| 代碼複雜度 | 較高,多臨時數組、偏移邏輯 | 低,單數組、無偏移 |
| 數據類型要求 | char 足夠 | 必須用 int 以上 |
| 擴展性 | 適合大數加減乘除通用框架 | 專用於乘法,加法需單獨實現 |