题目描述
计算数字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 static int digitCounts(int k, int n) {
// write your code here
int res = 0;
while(n>=0){
int temp = n;
while (temp>0){
if(temp%10==k){
res++;
}
temp/=10;
}
n--;
}
if (k==0){
return res+1;
}
return res;
}