java 将迭代函数转换为递归函数

ltskdhd1  于 2023-01-04  发布在  Java
关注(0)|答案(1)|浏览(110)

有人能把这个迭代函数转换成递归函数吗?谢谢

int b = 1; //what should be converted from
for(int i=0;i<=k;i++){
  b=b+1+b;  
}

我试过了,但是得到了一个整数溢出,所以很明显我做错了什么

public static int o(int k){ //recursive try
  if(k<0) return -1;
  else{
    if(k==0) return 1;
    else return o(k+1+k);  
  }  
}

有人能把这个迭代函数转换成递归函数吗?谢谢

a8jjtwal

a8jjtwal1#

下面是一个例子,展示了迭代和递归版本中的"堆栈跟踪":

public static void main(String[] args) {
    int k = 7;

    int b = 1;
    System.out.println("Starting Conditons:");
    System.out.println("b: " + b + ", k: " + k);
    System.out.println("Iterative trace:");
    for(int i=0;i<=k;i++){      
      b=b+1+b;  
      System.out.println("i: " + i + ", b: " + b);
    }
    System.out.println("Iterative: b = " + b);

    b = 1;
    System.out.println();
    System.out.println("Starting Conditons:");
    System.out.println("b: " + b + ", k: " + k);
    System.out.println("Recursive trace:");    
    b = foo(0, k, b);
    System.out.println("Recursive: b = " + b);
  }

  public static int foo(int i, int k, int b) {    
    System.out.println("i: " + i + ", b: " + b);
    if (i > k) {
      return b;
    }
    else {      
      return foo(i+1, k, b+1+b);
    }
  }

输出:

Starting Conditons:
b: 1, k: 7
Iterative trace:
i: 0, b: 3
i: 1, b: 7
i: 2, b: 15
i: 3, b: 31
i: 4, b: 63
i: 5, b: 127
i: 6, b: 255
i: 7, b: 511
Iterative: b = 511

Starting Conditons:
b: 1, k: 7
Recursive trace:
i: 0, b: 1
i: 1, b: 3
i: 2, b: 7
i: 3, b: 15
i: 4, b: 31
i: 5, b: 63
i: 6, b: 127
i: 7, b: 255
i: 8, b: 511
Recursive: b = 511

相关问题