采用《编程之美》的算法,但是这个算法会在自动统计置零位。例如9会当作09处理,从而多统计一个0。所以在统计完成后对count的值再调整。
代码如下。
class Solution {
public:
/*
* @param : An integer
* @param : An integer
* @return: An integer denote the count of digit k in 1..n
*/
int digitCounts(int k, int n) {
// write your code here
int count = 0;
int base = 1;
while(n/base>0){
int cur = (n/base)%10;
int high = n/(base*10);
int low = n - (n/base)*base;
if (cur == k){
count += high * base + low + 1;
} else if (cur<k){
count += high*base;
}else {
count += (high+1)*base;
}
base *= 10;
}
if (k==0 & n!=0){
count -= base/10;
}
else if (k==0 && n==0){
count = 1;
}
return count;
}
};
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。