首页 > 其他 > 详细

Digit Counts

时间:2020-04-28 10:12:33      阅读:65      评论:0      收藏:0      [点我收藏+]

Description

Count the number of k‘s between 0 and nk 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类型的,然后遍历一下即可~

 

Digit Counts

原文:https://www.cnblogs.com/WakingShaw/p/12791895.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!