"1234") 轉為對應整數值 (1234)處理字串 "1234":
初始累積值 = 0
讀 '1' → 0*10 + 1 = 1
讀 '2' → 1*10 + 2 = 12
讀 '3' → 12*10 + 3 = 123
讀 '4' → 123*10 + 4 = 1234
字串結束 → 返回 1234
#include
/**
* 遞迴字串轉整數
* @param str 當前處理位置指標
* @param acc 累積值 (初始呼叫傳 0)
* @return 解析後的整數值
*/
int strToIntRecursive(const char *str, int acc) {
// 基底情況:字串結束 (\0)
if (*str == '\0') {
return acc;
}
// 當前字元轉數字 (假設輸入合法數字字元)
int digit = *str - '0';
// 尾遞迴:累積值 * 10 + 當前位,指標前移
return strToIntRecursive(str + 1, acc * 10 + digit);
}
int main() {
char str[] = "1234";
int result = strToIntRecursive(str, 0);
printf("字串 \"%s\" 轉整數 = %d\n", str, result);
return 0;
}
| 遞迴層級 | str 指向 | acc (累積值) | digit | 新 acc | 動作 |
|---|---|---|---|---|---|
| 1 | '1' | 0 | 1 | 1 | 遞迴(str+1, 1) |
| 2 | '2' | 1 | 2 | 12 | 遞迴(str+1, 12) |
| 3 | '3' | 12 | 3 | 123 | 遞迴(str+1, 123) |
| 4 | '4' | 123 | 4 | 1234 | 遞迴(str+1, 1234) |
| 5 | '\0' | 1234 | - | - | 返回 1234 |
int strToIntSafe(const char *str, int acc, int *error) {
if (*str == '\0') return acc;
if (*str < '0' || *str > '9') { *error = 1; return 0; } // 非法字元
// 檢查溢位 (INT_MAX = 2147483647)
if (acc > (INT_MAX - (*str - '0')) / 10) { *error = 2; return 0; }
return strToIntSafe(str + 1, acc * 10 + (*str - '0'), error);
}
遞迴實作字串轉整數的核心是 **「左到右掃描、累積值 × 10 + 當前位」**。使用尾遞迴 + 累積器參數可獲得清晰、高效且符合「無迴圈」限制的解法。實際專案中建議加入邊界檢查 (空指標、非法字元、溢位)。