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 FIVE1's (1, 10, 11, 12)
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 result = 0;
int base = 1;
while (n/base > 0) {
int cur = (n/base)%10;
int low = n-(n/base) * base;;
int high = n/(base * 10);
if (cur < k)
{
result += high*base;
}
else if (cur > k)
{
result += (high+1)*base;
}
else
{
result += high*base+low+1;
}
base *= 10;
}
return result;
}
};