Description
Count the number of k's between 0 and n. k can be 0 - 9.
Example :
实在是想不通这道题为啥会是mid难度的,不就一个遍历的事吗。。。
在0~n个数字中,看看数字k出现的频次是多少。但是这个n,我们并不知道有多大,不知道是几位数,所以我个人觉得可以转换为:把0~n拼接为一个字符串,然后统计字符k在这个字符串中出现的频率即可:
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 StringBuilder sb = new StringBuilder(); for(int i = 0; i <= n; i++) { sb.append(i); } String s = sb.toString(); int count = 0; String str = ""; str += k; char c = str.charAt(0); for(int j = 0; j < s.length(); j++){ if (c == s.charAt(j)){ count++; } } return count; } }
用StringBuilder来拼接,可大幅度减少内存,拼接完成之后再转换为String类型的,然后遍历一下即可~