【Lintcode】003.Digit Counts

题目:

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)

题解:

Solution 1 ()

class Solution {
public:
    int digitCounts(int k, int n) {
        if (n < 0) {
            return 0;
        }
        int cnt = 0;
        for (int i = 1; i <= n; i++) {
            int num = i;
            while (num) {
                if (num % 10 == k) {
                    cnt++;
                }
                num = num / 10;
            }
        }
        if (k == 0 && n >= 0) {
            cnt++;
        }
        return cnt;
    }
};

 

posted @ 2017-05-19 22:34  Vincent丶丶  阅读(143)  评论(0编辑  收藏  举报