首页 > 代码库 > 【Lintcode】003.Digit Counts

【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;
    }
};

 

【Lintcode】003.Digit Counts