计算数字k在0到n中的出现的次数,k可能是0~9的一个值
Count the number of k's between 0 and n. k can be 0 - 9.
Example
if n = 12
, k = 1
in
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
we have FIVE 1's (1, 10, 11, 12)
我的解决方法:直接暴力解决,让每一个数字分别拆分比较,把0拿出来单独比对。
public class Solution {
/**
* @param k: An integer
* @param n: 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;
for(int m = n;m>=0;m--){
if(k==0&&m==0){
count++;
}
int num = m;
//将数由最低位依次向最高位每位的数字拿出来比较
while(num!=0){
if(num%10==k){
count++;
}
num=num/10;
}
}
return count;
}
}