給定正整數 A、DA、B、DB。定義 A 的「DA 部分」PA 為:由 A 中所有數字 DA 組成的新整數。例如 A=3862767, DA=6,則 PA=66。同理求 PB,輸出 PA + PB。
輸入範圍:0 < A, B < 10^10,超出 32 位整數範圍,必須用字串處理。
A, B 讀為字串。'0'+DA),則累計計數。cnt,構建結果數:result = result * 10 + DA 循環 cnt 次。A, DA 和 B, DB 分別執行上述邏輯,最後相加輸出。scanf("%s", str) 讀完字串後,緩衝區留有空格/換行,後續 scanf("%c", &ch) 會讀到空格。解法:scanf(" %c", &ch) 格式串前加空格,跳過空白字元。A, DA 後,計數器 count、構建值 k 必須歸零,否則第二組 B, DB 計算錯誤。scanf("%s", str) 中 str 已是首地址,不可 再加 &。#include <stdio.h>
#include <string.h>
int buildPart(char *numStr, char targetDigit) {
int count = 0;
for (int i = 0; numStr[i]; i++) {
if (numStr[i] == targetDigit) count++;
}
int val = 0;
for (int i = 0; i < count; i++) {
val = val * 10 + (targetDigit - '0');
}
return val;
}
int main() {
char A[12], B[12];
char DA, DB;
// 讀取 A DA B DB,注意 %c 前有空格吸收空白
scanf("%s %c %s %c", A, &DA, B, &DB);
int PA = buildPart(A, DA);
int PB = buildPart(B, DB);
printf("%d\n", PA + PB);
return 0;
}
| 輸入 | PA | PB | 輸出 |
|---|---|---|---|
| 3862767 6 13530293 3 | 66 | 333 | 399 |
| 3862767 1 13530293 8 | 0 | 0 | 0 |
O(N),N 為數字位數上限(此處 ≤ 10)。O(1),僅使用固定大小字元陣列與少量變數。本題核心考察字串處理細節與邊界條件控制,掌握 scanf 格式串技巧與模組化函式設計是關鍵。