剑指offer-chapter3-面试题12-打印1到最大的n位数(java)

本文介绍了一种打印从1到最大n位数的方法,通过使用BigInteger类解决整数溢出问题,适用于大范围数字的输出。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目:

输入数字n,按顺序打印出1到最大的n位十进制数。比如输入3,则打印1,2,3…999

陷阱:

考虑int 或long类型溢出必须使用字符模拟加减操作或使用java包

解法

  1. 使用BigInteger等类
  2. 使用数组进行递归操作 new char[n] char int都行 每一位进行+1打印

代码:

package problem12;

import java.math.BigInteger;

/**
 * Created by fengyuwusong on 2018/1/31 13:45.
 * 题目:打印1到最大的n位数
 * 输入数字n,按顺序打印出1到最大的n位十进制数。比如输入3,则打印1,2,3...999
 *
 * 陷阱
 * 考虑int 或long类型溢出必须使用字符模拟加减操作或使用java包
 *
 * 解法:
 * 1.使用BigInteger等类
 * 2.使用数组进行递归操作   new char[n] char int都行 每一位进行+1打印
 */

public class Main {
    public void PrintToMaxOfNDigits(int n){
//        边界判断
        if (n<0){
            throw new RuntimeException("参数n不能小于0");
        }
        BigInteger bigInteger=BigInteger.ZERO;
        int target=1;
        while (n!=0){
            target*=10;
            n--;
        }
        for (int i = 1; i <target ; i++) {
            bigInteger=bigInteger.add(BigInteger.ONE);
            System.out.println(bigInteger);
        }
    }

    public static void main(String[] args) {
        Main main=new Main();
        main.PrintToMaxOfNDigits(1);
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值