Tuesday, July 14, 2015

Digit Counts

Count the number of k's between 0 and n. k can be 0 - 9.
Have you met this question in a real interview? 
Yes
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)
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) {
        // write your code here
        int base = 1; 
        int result = 0;
        while(base <= n){
            int cur = n / base % 10;
            int low = n % base;
            int high = n / (base * 10);
            if(cur == k){
                result += high * base + low + 1;
            } else if(cur > k){
                result += high * base + base;
            } else {
                result += high * base; 
            }
            base *= 10;
        }
        return result;
    }



};

1 comment: