Lintcode : 统计数字

统计数字

计算数字k在0到n中的出现的次数,k可能是0~9的一个值

您在真实的面试中是否遇到过这个题? 
Yes
样例

例如n=12,k=1,在 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12],我们发现1出现了5次 (1, 10, 11, 12)

标签   Expand  

相关题目   Expand  

Timer Expand 


当某一位的数字小于i时,那么该位出现i的次数为:更高位数字x当前位数
当某一位的数字等于i时,那么该位出现i的次数为:更高位数字x当前位数+低位数字+1
当某一位的数字大于i时,那么该位出现i的次数为:(更高位数字+1)x当前位数
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 res = 0;
		int base = 1;
		if(n==0&&k==0) return 1;
		while(n/base>0){
			int curBit = (n/base)%10;
			int low = n - (n/base)*base;
		    int high = n/(base*10);
			if (curBit < k) {
				res += high*base;						
			} else if (curBit == k) {
				res += high*base+low+1;
			} else {
				if(k==0&&high==0){
					
				}else{
					res += (high+1)*base;
				}
			}
			base *=10;
		}
		return res;
    }
};


你可能感兴趣的:(LintCode,算法,面试)