简体   繁体   English

java简单递归

[英]java Simple recursion

So there is a recursive method (can not use any loop), that has one parameter n, and the program will print out 2^n "*", for example, if n was 2, the output is ****, and if n was 3, the output is ********. 因此,有一个递归方法(不能使用任何循环),它具有一个参数n,程序将输出2 ^ n“ *”,例如,如果n为2,则输出为****,并且如果n为3,则输出为********。

I'm stuck with this problem because I ran into some infinite recursion issues. 我陷入这个问题是因为我遇到了一些无限递归问题。

First I had this: but I soon realize that n will never reach the check. 首先我有这个:但是我很快意识到n永远不会到达支票。

在此处输入图片说明

↑↑↑ That was supposed to be n+1 (even though it doesn't work) ↑↑↑应该是n + 1(即使它不起作用)

Then I tried this: 然后我尝试了这个:

public class test {

    public static void main(String[] args) {
        printPowerOfTwoStars(3);

    }

    public static void printPowerOfTwoStars(int n){
        n = (int)Math.pow(2, n);
        if(n == 0){
            return;
        }
        else{
            System.out.print("*");
            printPowerOfTwoStars(n-1);
        }

    }

}

Ran into some infinite recursion again. 再次陷入无限递归。

This seems like a simple program with simple logic, but I'm having trouble with the condition check, because what's being compared with n keeps changing. 这似乎是一个具有简单逻辑的简单程序,但是我在条件检查方面遇到了麻烦,因为与n比较的内容一直在变化。

How should I fix this problem? 我应该如何解决这个问题?

Without using any helper method or creating any static variables. 无需使用任何辅助方法或创建任何静态变量。

Thank you 谢谢

You need to use the fact that 2 to the power of n is just 2 to the power of n-1 , doubled. 您需要利用以下事实: n的2乘以n-1乘以2。 Your base case is that 2 to the power of 0 is 1. 您的基本情况是2等于0的幂。

public static void printPowerOfTwoStars(int n){
    if(n <= 0){
        System.out.print("*");
    }
    else{
        printPowerOfTwoStars(n-1);
        printPowerOfTwoStars(n-1);
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM