簡體   English   中英

Java遞歸輸出數字模式

[英]Java recursion to output number pattern

要求的輸出:

    5
   454
  34543
 2345432
123454321

我該如何使用遞歸呢? 我有代碼的想法是:

public static void main(String[] args)
{
      System.out.println(func(5)); 
}
public static String func(int num)
{
     return num + "" +meth(num-1, num, num-1);
}

public static String meth(int start, int num, int end)
{

    if(start==1)
    {
        return "1";
    }
    System.out.println(start+num+end);

    return meth(start-1, num, end-1);
}

我對if語句和System.out.println()中的返回值感到困惑,因為數字5不會減少/增加,因為它將保持不變,例如它將垂直保持為5,我該如何處理問題? 我的代碼只是為了說明我正在做的例子。

也許這就是您想要的:

public class Main {
    public static void main(String[] args) {
        startRecursion(5);
    }

    private static void startRecursion(int number) {
        String aligner = "";
        for (int i = 0; i < number - 1; i++) {
            aligner += " ";
        }
        recursion(String.valueOf(number), number, number, aligner);
    }

    private static void recursion(String value, int startNumber, int lastNumber, String aligner) {
        if (lastNumber < 1) {
            return;
        }

        if (lastNumber != startNumber) {
            value = lastNumber + value + lastNumber;
        }

        System.out.println(aligner + value);

        if (!aligner.isEmpty()) {
            aligner = aligner.substring(0, aligner.length() - 1);
        }

        recursion(value, startNumber, lastNumber - 1, aligner);
    }
}

印刷品:

    5
   454
  34543
 2345432
123454321

我認為只是通過參數和前一個String(這是前一行)傳遞num:

private static String meth(int num,String previous) {

     String space="";
    for(int i=0; i<num; i++) space+=" ";
    //If number is negative, return empty String
    if(num<=0) return "";

    //if number is 1, we need to check if previous string is empty or not, because if is empty we need then umber only once, otherwise we need to add to the string
    else if(num==1){
        if(!previous.isEmpty()) return space+num+previous+num;
        else return space+num+"";
    }

    //Here is checked if previous is empty and we do the same as before with number one
    String currentRow=previous.isEmpty()? String.valueOf(num) : num+previous+num;

    //We return the current row (with the current number), and we add the next row (or tree level) passing the number-1 and the row we have
    return space+currentRow+"\n"+meth(num-1,currentRow);

}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM