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;
    }
};


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值