Java之递归求和的两张方法
方法一:
package com.smbea.demo; public class RecursionTest1 { private int sum = 0; /** * 递归求和 * @param num */ public void sum(int num) { this.sum += num--; if(0 < num){ sum(num); } else { System.out.println("sum = " + sum); } } }
方法二:
package com.smbea.demo; public class RecursionTest2 { public static void main(String[] args) { Teacher teacher = new Teacher(); teacher.sum(); } public static int sum(int num){ if(1 == num){ return 1; } else { return num + sum(num - 1); } }; }
当然还有其它方法,如采用 for 循环、while 循环等,那就不属于递归了!这里就不做讨论了。