給定 n 個正整數,需找出組成這些數字所用的 0~9 十個數字中,出現次數最多與最少的數字。這是一個典型的數字頻率統計問題。
使用長度為 10 的整型陣列 count[10] 記錄每個數字(0-9)的出現次數。遍歷每個輸入整數,通過取模(% 10)與除以 10(/ 10)迭代提取每一位數字,累加對應計數器。最後遍歷 count 陣列找出最大值與最小值對應的數字即可。
public static void findDigitFrequency(int[] nums) {
int[] count = new int[10];
for (int num : nums) {
int temp = num;
if (temp == 0) { // 特殊處理數字 0 本身
count[0]++;
continue;
}
while (temp > 0) {
int digit = temp % 10;
count[digit]++;
temp /= 10;
}
}
int maxDigit = 0, minDigit = 0;
for (int d = 1; d < 10; d++) {
if (count[d] > count[maxDigit]) maxDigit = d;
if (count[d] < count[minDigit]) minDigit = d;
}
System.out.println("出現最多: " + maxDigit + " (" + count[maxDigit] + "次)");
System.out.println("出現最少: " + minDigit + " (" + count[minDigit] + "次)");
}
此方法簡單高效,適合處理大量整數的數字頻率統計場景。