Digit Count

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)

Solution:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
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
int count = 0;

for (int i = 0; i <= n; i++){
count += countK(i,k);
}

return count;
}

private int countK(int i, int k){
if (i == 0 && k == 0)
return 1;

int count = 0;

while (i > 0){
count += i % 10 == k ? 1 : 0;
i /= 10;
}

return count;
}
};