LintCode: 统计数字

题目:要求统计0-n内k存在的次数,如0-11中1存在4次

分析:遍历0-n的每个数,然后对每个数进行数字统计,得到的结果相加。其中,对一个数进行数字统计可使用/%法,即第一次%得到个位,然后/再%,得到十位,然后/再%,得到百位,以此类推。

代码:

public class Solution {
    /*
     * @param : An integer
     * @param : 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++) {
            count += countOne(k, i);
        }
        return count;
    }
    
    public int countOne(int k, int n) {
        // 注意:有一种情况是:k和n同时为0,这时返回1
        if (k == 0 && n == 0)
            return 1;
            
        int count = 0;
        while (n > 0) {
            if (n % 10 == k)
                count++;
            n /= 10;
        }
        return count;
    }
};


猜你喜欢

转载自blog.csdn.net/cblstc/article/details/79135287