题目描述
计算数字 k 在 0 到 n 中的出现的次数,k 可能是 0~9 的一个值。
样例1
输入:
k = 1, n = 1
输出:
1
解释:
在 [0, 1] 中,我们发现 1 出现了 1 次 (1)。
样例2
输入:
k = 1, n = 12
输出:
5
解释:
在 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12] 中,
我们发现 1 出现了 5 次 (1, 10, 11, 12)(注意11中有两个1)。
java题解
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 cnt = 0;
for (int i = k; i <= n; i++) {
cnt += singleCount(i, k);
}
return cnt;
}
public int singleCount(int i, int k) {
if (i == 0 && k == 0)
return 1;
int cnt = 0;
while (i > 0) {
if (i % 10 == k) {
cnt++;
}
i = i / 10;
}
return cnt;
}
};
C++题解
class Solution {
public:
// param k : description of k
// param n : description of n
// return ans a integer
int digitCounts(int k, int n) {
int count = 0;
if (k == 0) {
count = 1;
}
for (int i = 1; i <= n; i++) {
int number = i;
while (number > 0) {
if (number % 10 == k) {
count += 1;
}
number /= 10;
}
}
return count;
}
};
python题解
class Solution:
# @param k & n two integer
# @return ans a integer
def digitCounts(self, k, n):
assert(n >= 0 and 0 <= k <= 9)
count = 0
for i in range(n + 1):
j = i
while True:
if j % 10 == k:
count += 1
j /= 10
if j == 0:
break
return count