首页 > 解决方案 > 将迭代变成递归

问题描述

再会!

我刚刚编写了一个代码作为迭代,它应该总结 0 和 y 之间的偶数。

我现在已经在办公桌上坐了大约两个小时,思考如何在递归中编写相同的代码——到目前为止没有任何进展。我在互联网上找到的唯一解释解释了一个特定更改的简单重复 - 不像我的代码包含两个。("result = result + x;" and "x = x + 2;" ) 有人可以向我解释一下如何将这种迭代转化为递归吗?提前致谢!

 public class Sum {

   static int method(int y) { 
     int result = 0; 
     for (int x = 2; x<=y;)
     {
        result = result + x;   
        x = x + 2; 
     }
     return result;
   } 

   public static void main(String[ ] args) {
      int result = method(35); 
      System.out.println("Sum of even numbers between 0-35: " +result); 
   }
}

标签: javarecursionintreturniteration

解决方案


数字的总和就是这个数字的总和加上这个数字的总和减2。写在代码中:

int method(int y) { 
  if (y <= 0) {
     return 0;
  } else {
     return y + method(y - 2);
  }
} 

不用说,这种形式的递归是不必要的,并且会创建StackoverflowException一个y非常大的数字。某些语言允许您编写递归函数并指示它是尾递归,以便编译器实际上将其转换为迭代。


推荐阅读