題目鏈接:
https://www.lintcode.com/problem/digit-counts/description
描述
計算數(shù)字k在0到n中的出現(xiàn)的次數(shù),k可能是0~9的一個值
您在真實的面試中是否遇到過這個題? 是
樣例
例如n=12,k=1,在 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12],我們發(fā)現(xiàn)1出現(xiàn)了5次 (1, 10, 11, 12)
代碼實現(xiàn):
package 中等題1;
import java.util.ArrayList;
import java.util.List;
public class Main {
public static void main(String[] args) {
int k = 1;
int n = 12;
System.out.println(digitCounts(1,12));
}
public static int digitCounts(int k, int n) {
int num = 0;
for (int i = k; i <= n; i++){
//整數(shù)變成字符串
String s = String.valueOf(i);
//字符串變成字符數(shù)組
char[] ss = s.toCharArray();
for (int j = 0; j < s.length(); j++){
//字符變成整數(shù)
int a = Character.getNumericValue(ss[j]);
if (a == k){
num++;
}
}
}
return num;
}
}
代碼實現(xiàn)2:數(shù)學(xué)方法獲得)通過與10的余數(shù)得到末位,通過與10除去掉末位,構(gòu)成一個循環(huán),就可以分析一個數(shù)的所有位。然后把所有位都加起來(從局部到整體)
public int digitCounts(int k, int n) {
int cnt = 0;
for (int i = k; i <= n; i++) {
//分次計算每一個數(shù)中含有k的個數(shù)
cnt += singleCount(i, k);
}
return cnt;
}
public int singleCount(int i, int k) {
//排除0的情況
if (i == 0 && k == 0)
return 1;
int cnt = 0;
while (i > 0) {
//判斷末尾是否為k
if (i % 10 == k) {
cnt++;
}
//去掉末尾再次循環(huán),直到去除完所有位跳出循環(huán)
i = i / 10;
}
return cnt;
}