Lintcode Digit Counts

http://www.lintcode.com/en/problem/digit-counts/

 

枚举,有三种情况。

第一种情况是当前位小于k,则此时该位上的计数取决于高于该位的数值;

第二种情况,当前位等于k,则此时该位上的计数取决于高于该位的和低于该位的;

第三种情况,当前位大于k,则此时该位的计数取决于高位

 

比较好想,下面是代码

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
        long long base = 1;
        
        int res = 0;
        while (base <= n){
            int cur = (n / base) % 10;
            
            int high = n / base / 10;
            int low = n % base;
            
            if (cur > k) res += (high + 1) * base;
            else if (cur == k) res += (low + 1) + high * base;
            else res += high * base;
            
            base *= 10;
        }
        
        return res;
    }
};

 

posted @ 2015-06-21 13:04  EpisodeXI  阅读(207)  评论(0编辑  收藏  举报