計算數字k在0到n中的出現的次數,k可能是0~9的一個值
樣例
例如n=12,k=1,在 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12],我們發現1出現了5次 (1, 10, 11, 12)
public int digitCounts(int k, int n) {
int count = 0;
//循環從n->0,每個數和k比較
while(n >= 0){
count += isDigit(k,n);
n--;
}
return count;
}
public static int isDigit(int k ,int n){
int time = 0; //記錄單個數出現k的次數
while(n > 9){
if(n % 10 == k) // n%10得到最後一位,與k進行比較
time++;
n /= 10; // n/10去掉最後一位
}
if(n == k) //當n只剩一位時,與k比較
time++;
return time;
}