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)
We need to consider the problem digit by digit.
Using k = 1 as an example. Let's say n = 113.
Time: O(logN)
Space: O(1)
class Solution {
public int digitCounts(int k, int n) {
int count = 0;
for (long base = 1; base <= n; base *= 10) {
long higher = n / base;
long lower = n % base;
if (higher % 10 > k) {
count += (higher / 10 + 1) * base;
} else {
count += (higher / 10) * base;
}
if (higher % 10 == k) {
count += lower + 1;
}
}
return count;
}
}