【解题报告】lintcode3统计数字
题意
给出一个n和k,统计0-n的数字中,k出现了多少次
解题
首先通过log运算来得出n有多少位,创建数组,每次给数组最低位加1
然后计算进位
在计算过程中,计算数字出现次数
代码
class Solution {
/*
* param k : As description.
* param n : As description.
* return: An integer denote the count of digit k in 1..n
*/
public int digitCounts(int k, int n) {
// write your code here
if (n == 0&&k == 0)
return 1;
if (n == 0&&k != 0)
return 0;
int dig = (int)(Math.log(n)/Math.log(10)) +1;
int[] num = new int[dig];
int count = 0,i = 0,digs = 1;
while (i < n){
num[0]++;
i++;
for (int j = 0;j < digs&&j < num.length;j++){
if (num[j] >= 10){
if (j < num.length - 1)
num[j+1] += num[j]/10;
num[j] %= 10;
if (j == (digs -1))
digs++;
}
if (num[j] == k)
count++;
}
}
if (k == 0)
count++;
return count;
}
};