计算从 1 -n 中1出现的次数

1. 个位出现1的个数为 1
2. 十位出现1的个数为10
3. 百位出现1的个数为100

综上所述 每个位出现 一个数的次数为 10^(i-1)
设置 当前数位上的数 为tmp
设置 出现数位 n
tmp<n 则受高位上的数的影响  高位数*10^(i-1)

tmp>n 则受高位上的数与低位数的影响  高位数*10^(i-1)+10^(i-1)

tmp=n 则受高位上的数与低位数的影响  相对来说复杂一点 ,需要计算后面影响的数  高位数*10^(i-1)+ 低位数 + 1

代码如下:

 public int numberOf1Between1AndN(int n, int x){
        if(n < 0 || x < 1 || x > 9){
            return 0;
        }
        int curr, low, temp, high = n, i = 1, total = 0;
        while(high!=0){
            high = n / (int)Math.pow(10, i); //获取第i位的高位
            temp = n % (int)Math.pow(10, i); //  获取低位中的数
            curr = temp / (int)Math.pow(10, i-1); //获取第i位
            low = temp%(int)Math.pow(10, i-1); //获取第i位的低位
            if(curr == x){ //等于x
                total += high*(int)Math.pow(10, i-1)+ low + 1;
            }else if(curr < x){ //小于x
                total += high*(int) Math.pow(10, i-1);
            }else{ //大于x
                total += (high + 1) * (int)Math.pow(10, i-1);
            }
            i++;
        }
        return total;
    }

    public static void main(String[] args) {
        Main1 m1 = new Main1();
        int nums = m1.numberOf1Between1AndN(155, 2);
        System.out.println(nums);
    }

猜你喜欢

转载自blog.csdn.net/wt5264/article/details/108486386