lintcode:Digit Counts

来源:互联网 发布:淘宝苏宁买手机可靠吗 编辑:程序博客网 时间:2024/05/15 10:03

Count the number of k's between 0 and n. k 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 FIVE1's (1, 10, 11, 12)


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


0 0
原创粉丝点击