剑指Offer-17-打印从1到最大的n位数-Java代码实现(两种思路)

剑指Offer 17题

打印从1到最大的n位数
  • 题目描述

    输入数字 n,按顺序打印出从 1 到最大的 n 位十进制数。比如输入 3,则打印出 1、2、3 一直到最大的 3 位数 999。来源于LeetCode

    示例 1:

    输入: n = 1
    输出: [1,2,3,4,5,6,7,8,9]

  • 代码实现(两种思路)

    import java.util.Arrays;
    public class Test17 {
        public static void main(String[] args) {
            int[] res = PrintNumbers2(1);
            System.out.println(Arrays.toString(res));
        }
    
        //思路1
        public static int[] PrintNumbers(int n){
            String s = "";
            for(int i = 0; i < n; i++){
                s += "9";
            }
            int end = Integer.valueOf(s);
            int[] res = new int[end];
            for(int i = 0; i < res.length; i++){
                res[i] = i+1;
            }
            return res;
        }
        
        //思路2
        public static int[] PrintNumbers2(int n){
            int end = (int)Math.pow(10,n) - 1;
            int[] res = new int[end];
            for(int i = 0; i < res.length; i++){
                res[i] = i+1;
            }
            return res;
        }
    }
    
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值