递归调用

 1 public class TestRecursion01 {
 2 
 3     public static void main(String[] args) {
 4         long d1 = System.currentTimeMillis();
 5         System.out.printf("%d阶乘的结果:%s%n",10,factorial(10));
 6         long d2 = System.currentTimeMillis();
 7         System.out.printf("递归费时%s%n",d2-d1);
 8     }
 9     static long factorial(int n) {
10         if(n == 1) {//递归头
11             return 1;
12         }else {//递归体
13             return n*factorial(n-1);
14         }
15         //1*2*3*....*10
16     }
17 }
执行结果:
          

注意事项:

    任何能用递归解决的问题,也能使用迭代解决。

    在要求高性能的情况下,应尽量避免使用递归。递归既耗时又消耗内存。


原文地址:https://www.cnblogs.com/fax1996/p/9304822.html