码迷,mamicode.com
首页 > 其他好文 > 详细

Digit Counts

时间:2016-07-06 09:52:13      阅读:180      评论:0      收藏:0      [点我收藏+]

标签:

Count the number of k‘s between 0 and nk can be 0 - 9.

Example

if n = 12, k = 1 in

[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]

we have FIVE 1‘s (1, 10, 11, 12)

分析:

利用while 循环 + num % 10可以获取 num中的所有数字。

class Solution {
    /*
     * param k : As description.
     * param n : As description.
     * return: An integer denote the count of digit k in 1..n
     */
    public int digitCounts(int k, int n) {
        int totalCount = 0;
        for (int i = 0; i <= n; i++) {
            totalCount += counts(k, i);
        }
        return totalCount;
    }
    
    public int counts(int k, int value) {
        int count = 0;
        if (value == 0 && k == 0) return 1;
        while (value != 0) {
            int remainder = value % 10;
            if (remainder == k) {
                count++;
            }
            value = value / 10;
        }
        return count;
    }
};

 

Digit Counts

标签:

原文地址:http://www.cnblogs.com/beiyeqingteng/p/5645582.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!