#3 Digit Counts

来源:互联网 发布:私下买卖淘宝店犯法吗 编辑:程序博客网 时间:2024/06/10 00:58

题目描述:

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)

题目思路:

这题。。我就是死做。。遍历0~n,每个数字都算一下k出现的次数,然后加起来。。

Mycode(AC = 130ms):

class Solution {public:    /*     * param k : As description.     * param n : As description.     * return: How many k's between 0 and n.     */    int digitCounts(int k, int n) {        // write your code here        int count = 0;        for (int i = 0; i <= n; i++) {            count += countHelper(to_string(i), k);        }        return count;    }        int countHelper(string num, int k) {        int count = 0;        for (int i = 0; i < num.size(); i++) {            if (num.substr(i, 1) == to_string(k)) {                count++;            }        }        return count;    }};


0 0