LintCode-3.统计数字
统计数字
计算数字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)
标签
枚举法
code
class Solution {
public:
/*
* param k : As description.
* param n : As description.
* return: How many k's between 0 and n.
*/
int digitCounts(int k, int n) {
// write your code here
int res = 0;
int base = 1;
if(n==0 && k==0)
return 1;
while(n/base>0) {
int curBit = (n/base);
int low = n - (n/base)*base;
int high = n/(base*10);
if (curBit < k) {
res += high*base;
}
else if (curBit == k) {
res += high*base+low+1;
}
else {
if(!(k==0 && high==0)) {
res += (high+1)*base;
}
}
base *=10;
}
return res;
}
};