描述
計算數字 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;
}
}