题目:计算数字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 class Solution {
/*
* @param : An integer
* @param : An integer
* @return: An integer denote the count of digit k in 1..n
*/
public int digitCounts(int k, int n) {
// write your code here
int count=0;
if(k==0){
count++;
}
for(int i=0;i<=n;i++){
/* if(i==k){
count++;
}*/
int m=i;
while(m>0){
if(m%10==k){
count++;
}
int a=m%10;
m=(m-a)/10;
}
}
return count;
}
};