簡體   English   中英

在遞歸方法中有一個變量不會在每次調用后重新定義自己

[英]having a variable in recursive method not redefine itself after each call

我將在下面發布我的代碼,因為這有點難以描述。 下面的代碼有效,但它在 main 方法中而不是在 helper 中使用 Math.pow,所以如果有人可以向我展示一種將權力轉移到 helper 方法的方法,我將不勝感激。

主要方法:

  Scanner keyboard = new Scanner(System.in);

  System.out.println("Please enter an integer: ");
  double input = keyboard.nextInt();

  double x = Math.pow(2.0, input);
  int n = (int)x;

  System.out.println(starStr(n));

輔助方法:

  public static String starStr(int n)
  {     
     if (n >= 1) {
        return ("*" + starStr(n-1));
     }
     else {
        return "";
     }
  }

編輯:

 if(n == 0) {
     return "*";
  }   
  else {
     return starStr(n - 1) + "**";
  }

像這樣的事情會起作用。 您根本不需要使用冪函數。 只需從 1 顆星開始,然后在遞歸的每一步中將星數加倍。

public static void main(String[] args) {

    Scanner keyboard = new Scanner(System.in);

    System.out.println("Please enter an integer for the number of stars: ");
    int input = keyboard.nextInt();

    System.out.println(doStars(input));
}

public static String doStars(int n)
{
    //If n == 0 the recursion is done
    //Otherwise, reduce n by 1 and double the number of stars
    if(n == 0)
        return "*";
    else
    {
        String output = doStars(n - 1);
        return output + output;
    }
}

我想這就是你要找的。 不確定您是否已經學習了樹數據結構,但這就是我的變量名稱的目的。

public class Main {
    public static void main(String[] args) {

        for (int i = 0; i < 5; i++) {
            // 1 + (2^n)-1 = 2^n 
            System.out.println("*" + doStars(i));
        }
    }

    public static String doStars(int n)
    {
        if (n == 0) {
            return "";
        }
        else {
            String subTree = doStars(n - 1); 
            return subTree + "*" + subTree; // length = (2^n)-1
        }
    }
}

輸出

*
**
****
********
****************

可視化- 在三角形中從小到大順時針閱讀

                        "*"
                         +
                     doStars(2)
                        "*"
      doStars(1)         +        doStars(1)
          "*"                         "*"
doStars(0) + doStars(0)     doStars(0) + doStars(0)
   ""           ""              ""          ""

暫無
暫無

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

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