輸入 N 個整數,統計所有數字的個位數字(0-9)出現頻次,輸出最高頻次及對應的數字(升序)。
cnt[10] = {0}cnt 找出最大值 max_cntmax_cnt 的數字#include <stdio.h>
int main(void) {
int n;
scanf("%d", &n);
int cnt[10] = {0};
int x;
for (int i = 0; i < n; i++) {
scanf("%d", &x);
// 處理 0 的特殊情況:0 的個位是 0
if (x == 0) {
cnt[0]++;
} else {
// 取絕對值處理負數(題目未明確是否有負數,保險起見)
if (x < 0) x = -x;
while (x > 0) {
cnt[x % 10]++;
x /= 10;
}
}
}
int max_cnt = 0;
for (int i = 0; i < 10; i++)
if (cnt[i] > max_cnt) max_cnt = cnt[i];
printf("%d:", max_cnt);
for (int i = 0; i < 10; i++)
if (cnt[i] == max_cnt) printf(" %d", i);
printf("\n");
return 0;
}
while(x>0) 會跳過 0,需單獨 if(x==0) cnt[0]++%10 得負餘數(C99 規定餘數符號同被除數)max_cnt: 後跟空格分隔的數字,升序自然由 0→9 遍歷保證輸入: 5 123 456 789 101 202 輸出: 3: 0 1 2 解析:個位數字分別為 3,6,9,1,2 → 0出現0次,1出現2次(101,123),2出現2次(202,123)…… 實際統計:0:1(101), 1:2(123,101), 2:2(123,202), 3:1, 4:0, 5:1(456), 6:1, 7:1(789), 8:1, 9:1 最大頻次為 2,對應數字 1 和 2 → 輸出 "2: 1 2" (注:樣例僅示意,實際需精確計算)