if n =12, k =1in

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

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

class Solution {
public:
    /*
     * @param k: An integer
     * @param n: An integer
     * @return: An integer denote the count of digit k in 1..n
     */
    int digitCounts(int k, int n) {
        // write your code here
        int count = 0;
        if (k == 0) {
            count = 1;
        }
        for (int num = 0; num < n+1; num++) {
            int number = num;
            while (number > 0 ) {
                if (number % 10 == k) {
                    count++;
                }
                number = number / 10;
            }        
        }
        return count;
    }
};

results matching ""

    No results matching ""