zoukankan      html  css  js  c++  java
  • [剑指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("
    ");
    	}
    }
    
    
  • 相关阅读:
    Python基础07
    python基础06
    python基础05
    python基础04
    python基础03
    python基础02
    python组件之wtforms
    PythonWeb框架之Flask
    Linux下yum安装Redis
    在vuex的mutations中使用vue的小技巧
  • 原文地址:https://www.cnblogs.com/coding-gaga/p/11167141.html
Copyright © 2011-2022 走看看