打印n位数字

package com.company;

public class Println {

    public static void main(String[] args){
//        printlnNumber(3);
        printlnNumber2();
    }

    public static void printlnNumber(int num){
        if(num <=0){
            System.out.println("位数小于0无法打印");
            return;
        }
        char[] chars = new char[num];
        for(int i = 0; i < chars.length; i++){
            chars[i] = '0';
        }
        while(inCrease(chars)){
            printlnChars(chars);
        }
    }
    public static boolean inCrease(char[] chars){
        boolean result = false;
        if(addAndJinwei(chars,chars.length-1)){
            return jingwei(chars,chars.length -2);
        }
        result = true;
        return result;
    }

    /**
     * 进位
     * @param chars
     * @param pos
     * @return
     */
    public static boolean jingwei(char[] chars,int pos){
        if(pos < 0) return false;
        if(addAndJinwei(chars,pos)){
            return jingwei(chars,pos-1);
        }
        return true;
    }

//0 = 48, 9 = 57

    /**
     * 某一位加1,然后返回需不需要进位。
     * @param chars
     * @param pos
     * @return
     */
    public static boolean addAndJinwei(char[] chars,int pos){
        if(chars[pos] ==57){
            chars[pos] = '0';
            return true;
        }else{
            int index = chars[pos] - 48+1;
            chars[pos] = getChar(index);
        }
        return false;
    }

    public static void printlnChars(char[] chars){
        String s = new String(chars);
        System.out.println("num = "+s);
    }

    public static char getChar(int index){
        char[] charSet = {48,49,50,51,52,53,54,55,56,57};
        return charSet[index];
    }


    public  static void printlnNumber2(){
        char[] threeChrs = new char[3];
        for(int i =0; i< threeChrs.length; i++){
            threeChrs[i] = 48;
        }
        singlePrint(threeChrs,3,0);
    }
    /**
     *   单次打印
     * @param chars 排列好的字符
     * @param n 表示排列的第几位
     */
    public static void singlePrint(char[] chars, int wei, int currentWei){
        //如果排列到最后一位就直接打印。
        if(wei <= 0 || currentWei > wei){
            System.out.println("参数错误");
            return;
        }
        if(currentWei == wei-1){
            for(char i = 48; i <= 57; i++){
                chars[currentWei] = i;
                printlnChars(chars);
            }
        } else {
            for(char i = 48; i <= 57; i++){
                chars[currentWei] = i;
                singlePrint(chars,wei,currentWei+1);
            }
        }
    }
}

两种实现方式都可以,如果要使用递归,首先需要分析题目,知道自己的解题思路,首先还是确定入参和出参,写出单次的过程,然后推广到下一部,并处理好递归终止条件

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值