java输入整数n,求1~n整数中数字1出现的次数

public static void find(){
        int total = 0;
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        for(int j = n; j >0; j--) {
          //int j = n;
            //算出是几位数
            int wei = 0;
            int num = j;
            while (num != 0) {
                num = num / 10;
                wei++;
            }
            //算出1的个数
            int mm = j;
            int tmp = wei;
            for (int i = 1; i <= tmp; i++) {
                int nn = (int) (Math.pow(10, wei - 1));
                if (mm / nn == 1) {
                    total += 1;
                    mm = (int) (mm % Math.pow(10, wei - 1));
                    wei--;
                } else {
                    mm = (int) (mm % Math.pow(10, wei - 1));
                    wei--;
                }
            }
        }
        System.out.println("从1~"+n+"一共出现了"+total+"次1.");
    }

猜你喜欢

转载自blog.csdn.net/weixin_40879743/article/details/89102142
今日推荐