题目描述:
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)
这题。。我就是死做。。遍历0~n,每个数字都算一下k出现的次数,然后加起来。。
Mycode(AC = 130ms):
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 count = 0;
for (int i = 0; i <= n; i++) {
count += countHelper(to_string(i), k);
}
return count;
}
int countHelper(string num, int k) {
int count = 0;
for (int i = 0; i < num.size(); i++) {
if (num.substr(i, 1) == to_string(k)) {
count++;
}
}
return count;
}
};