从1到n整数中1出现的次数

题目

输入一个整数n,求从1到n这n个整数的十进制表示中1出现的次数。例如输入12,从1到12这些整数中包含1的数字有1,10,11,12共出现5次

解题

这个题目比较难
直接暴力

public class Solution {
    public int NumberOf1Between1AndN_Solution(int n) {
        int count = 0;
        for(int i =1;i<=n;i++){
            count +=NumberOf1(i);
        }
        return count;
    }
    public int NumberOf1(int num){
        int count =0;
        while(num!=0){
            if(num%10==1){
                count++;
            }
            num/=10;
        }
        return count;
    }
}

对数字n,有 log(n)
对1到n内的数统计1的次数,时间复杂度就是 nlog(n)

编程之美上讲解很详细,不想敲字了

public class Solution {
    public int NumberOf1Between1AndN_Solution(int n) {
        int count = 0;
        int factor = 1;
        int low = 0;
        int cur = 0;
        int high = 0;
        while(n/factor!=0){
            cur = (n/factor)%10; //当前位
            low = n - (n/factor)*factor ;// 低位数字
            high = n/(factor*10); //更高位
            switch( cur){
                case 0:
                    count+= high* factor;
                    break;
                case 1:
                    count+= high* factor + low + 1;
                    break;
                default:
                    count +=(high+1) * factor;
                    break;
            }
            factor *=10;
        }
        return count;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值