剑指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; } }