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)
解法一:
1 class Solution { 2 public: 3 // param k : description of k 4 // param n : description of n 5 // return ans a integer 6 int digitCounts(int k, int n) { 7 int count = 0; 8 if (k == 0) { 9 count = 1; 10 } 11 for (int i = 1; i <= n; i++) { 12 int number = i; 13 while (number > 0) { 14 if (number % 10 == k) { 15 count += 1; 16 } 17 number /= 10; 18 } 19 } 20 21 return count; 22 } 23 };