1-n的整数中x出现的次数

求从1-n的整数中间,x出现的次数
例如:n=13,x=1,求1-13(包括1和13)中1出现的次数
1、10、11、12、13一共出现6次

方法:求每一位上x出现的次数,再相加
规律:
从右往左数第i位(i从0开始),记第i位左边的数是high,第i位右边的数是low,第i位的数是cur
第i位x出现的次数为:
1、cur < x
count = high * 10^i
2、cur > x
count = high * 10^i + 10^i
3、cur = x
count = high * 10^i + low + 1

例:1-21中出现1的次数(1、10、11、12、13、14、15、16、17、18、19,21一共为13次)
用公式验证:
从右往左第0位
high=2
cur=1(=x)
low=0
count=high*10^i+low+1=2*10^0+0+1=3
从右往左第1位
high=0
cur=2(>x)
low=1
count=high*10^i+10^i=0*10^1+10^1=10
一共出现3+13次
x=1的代码实现

    public int NumberOf1Between1AndN_Solution(int n) {
        int count = 0;
        int i = 0, high = n, low, temp, cur;
        while(high != 0) {
            high = n / (int)Math.pow(10, i + 1); //第i位左边的数
            temp = n % (int)Math.pow(10, i + 1); //第i位右边(包括i)的数
            cur = temp / (int)Math.pow(10, i); //第i位
            low = temp % (int)Math.pow(10, i);  //第i位右边的数
            count += high * (int)Math.pow(10, i);//基础数
            //System.out.println(temp + " " + high + " " + cur + " " + low + " " + count);
            if(cur > 1) {
                count += (int)Math.pow(10, i);
            }else if(cur == 1) {
                count += low + 1;
            }
            i++;
        }
        return count;
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值