描述
计算数字 k 在 0 到 n 中的出现的次数,k 可能是 0~9 的一个值。
样例
输入:
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)。
拿到题目的首先思路是将拿到的数字拆分, 那么将数字拆分有两种方式 :
1. 将数字转化成字符串/字符型数组拆分
2. 将数字每一位提取拆除
public class Solution {
/**
* @param k: An integer
* @param n: An integer
* @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++) {
int key = i;
while(key >= 1) {
int tmp = key%10;
if(k == tmp) {
count++;
}
key /= 10;
}
}
if(k == 0) {
count++;
}
return count;
}
}