剑指offer之面试题43:1~n整数中1出现的次数

面试题43:1~n整数中1出现的次数

题目:输入一个整数 n,求 1~n 这 n 个整数的十进制表示中 1 出现的次数。例如,输入 12,1-12 这些整数中包含 1 的数字有 1、10、11 和 12,1 一共出现了 5 次。

思路1:暴力解法,累加1-n中每个整数中1出现的次数。

代码实现:

package Question43;

public class T01 {
    public static void main(String[] args) {
        int n = 12;
        System.out.println(solve(n));
    }

    public static int solve(int n) {
        int count = 0;
        for(int i = 1; i <= n; i++) {
            int temp = i;
            while(temp > 0) {
                if(temp % 10 == 1) count++;
                temp /= 10;
            }
        }
        return count;
    }
}

思路2:数位统计

  • 以12345为例,假设要统计千位上的1的出现次数,即_ _x _ _
  • 若前两位为 0-11,后两位可以为0-99,所以出现次数为 12*100。
  • 若前两位为 12,则后两位只能为 0-45,所以出现次数为 46
  • 所以千位上能出现 1 的次数是1246。
  • 将所有位进行上述的计算即可。
  • 实际的情况更为复杂,以代码为主!!

代码实现:

package Question43;

public class T02 {
    public static void main(String[] args) {
        int n  = 999;
        System.out.println(solve(n));
    }

    public static int solve(int n) {
        if(n >= 0 && n <= 9) return n >= 1 ? 1 : 0;
        int count = 0;
        String num = String.valueOf(n);
        for(int i = 0; i < num.length(); i++) {
            if(i == 0) {
                String temp = num.substring(1);
                count += num.charAt(0) > '1' ? (int)Math.pow(10, temp.length()) : Integer.parseInt(temp) + 1;
            } else if(i == num.length() - 1) {
                String temp = num.substring(0, i);
                count += num.charAt(i) >= '1' ? Integer.parseInt(temp) + 1 : Integer.parseInt(temp);
            } else {
                int lval = Integer.parseInt(num.substring(0, i));
                int rval = Integer.parseInt(num.substring(i+1));
                count += lval * (int)Math.pow(10, num.substring(i+1).length());
                if(num.charAt(i) > '1') count += (int)Math.pow(10, num.substring(i+1).length());
                else count += num.charAt(i) == '1' ? rval + 1 : 0;
            }
        }
        return count;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值