[剑指Offer]17-打印从1到最大的n位数(递归)

题目

如题,输入n,则从1打印至99.

题解

考虑到n比较大会有大数问题,所以使用字符数组存储数。
由题可用递归求n位全排列,即为所得。
具体地,用临时字符数组用来存答案,每次递归填好一位,都填好后输出。

代码

import java.util.Scanner;

public class Main {
	public static void main(String[] args) {
		Scanner s=new Scanner(System.in);
		int n=s.nextInt();
		printToN(n);
	}
	
	public static void printToN(int n) {
		char[] num=new char[n];
		composeNum(num,0,num.length);
	}
	
	//len位全排列
	private static void composeNum(char[] num,int pos,int len) {
		if(pos==len) {//此位不需要再填,输出此时num即为所得
			printDelZero(num);
		}
		else {
			for(int i=0;i<10;++i) {
				num[pos]=(char) (i+'0');
				composeNum(num,pos+1,len);
			}
		}
	}
	
	//删除前面的0
	private static void printDelZero(char[] num) {
		int pos=0;
		for(;pos<num.length;++pos) {
			if(num[pos]!='0') {
				break;
			}
		}
		for(int i=pos;i<num.length;++i) {
			System.out.print(num[i]);
		}
		System.out.print("\n");
	}
}

posted on   coding_gaga  阅读(261)  评论(0编辑  收藏  举报

< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

导航

统计

点击右上角即可分享
微信分享提示