剑指offer31题 整数中1出现的次数(从1到n整数中1出现的次数)

题目地址

发现一种全新的计算方法:

在这里插入图片描述

package com.example.brushalgorithmproblem.swordtooffer;

/**
 * @author Duan Xiangqing
 * @version 1.0
 * @date 2021/3/12 11:43 下午
 */
public class JZ31 {

    //    抽象出数学计算模型 看不懂可以把下面的sout打开看看
    public static int NumberOf1Between1AndN_Solution(int n) {

        int sum = 0;
        int k = 1;

//        n=x+z+y
        int len = String.valueOf(n).length();
        for (int i = 0; i < len; i++) {
//            提取各数位
            int y = n % k;
            int x = n / (k * 10);
            int z = n % (k * 10) / k;

            if (z == 1) {
                sum = sum + x * k + y + 1;
            } else if (z == 0) {
                sum = sum + x * k;
            } else if (z > 1) {
                sum = sum + (1 + x) * k;
            }

//            System.out.println("x=" + x + " z=" + z + " y=" + y + " k=" + k);
            k = k * 10;
        }
        return sum;
    }


    //    转换成字符串计算
    public static int NumberOf1Between1AndN_Solution1(int n) {
        int sum = 0;

        for (int i = 1; i <= n; i++) {
            String st = String.valueOf(i);
            for (int j = 0; j < st.length(); j++) {
                if (st.charAt(j) == '1') {
                    sum++;
                }
            }
        }
        return sum;
    }

    //    利用求余和除法进行计算
    public static int NumberOf1Between1AndN_Solution2(int n) {
        int sum = 0;

        for (int i = 1; i <= n; i++) {
            int s = i;
            while (s > 0) {
                if (s % 10 == 1) {
                    sum++;
                }
                s /= 10;
            }
        }
        return sum;
    }


    public static void main(String[] args) {
        int n = 120120;

//        比较一下三种方法的运算时间
        Long start = System.currentTimeMillis();
        System.out.println(NumberOf1Between1AndN_Solution(n));
        System.out.println("Spending time: " + (System.currentTimeMillis() - start));
        System.out.println();

        start = System.currentTimeMillis();
        System.out.println(NumberOf1Between1AndN_Solution1(n));
        System.out.println("Spending time: " + (System.currentTimeMillis() - start));
        System.out.println();

        start = System.currentTimeMillis();
        System.out.println(NumberOf1Between1AndN_Solution2(n));
        System.out.println("Spending time: " + (System.currentTimeMillis() - start));
        System.out.println();

    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值