java中的2,4,8,...的递归方法

时间:2016-10-12 14:11:45

标签: java recursion

我需要为我的类编写一个递归方法。该方法应该打印序列1,2,4,8,16的前n个元素,所以如果调用该方法,例如:

recSeq(6);

该方法应打印:1,2,4,8,16,32 该方法声明如下:

static void recSeq(int n){

    //enter code here

}

我真的不知道如何在没有回报价值的情况下做到这一点?有什么想法吗?

2 个答案:

答案 0 :(得分:1)

递归函数。

127.0.0.1   ip-108-205-72-168
127.0.0.1   localhost localhost.localdomain localhost4 localhost4.localdomain4
::1         localhost6 localhost6.localdomain6

退出:

void recSeq(int counter){
        if (counter <= 0 ) return; // first the exit condition
        int value = counter -1; 
        recSeq(value ); // go down to the bottom, in order to print values from lovest values to higher
        System.out.print(" "+(int)Math.pow(2, value )); // print the value
 }

答案 1 :(得分:0)

static void recSeq(int n){
    if(n > 1){
        recSeq(n-1)
        System.out.print("," + Math.pow(2, n-1));
    } else {
        System.out.print(1);
    }
}