Recursion.
/** * sum from 1 to n. recursion * @param i * @return sum */ public int recur_head(int i){ System.out.println("i = "+ i); if(i==1) return 1; else return i+recur_head(i-1); }
tail Recursion.
/*** * sum from 1 to n. tail recursion * @param i * @param total * @return */ public int recur_tail(int i, int total){ System.out.println("i = "+ i+", total = "+ total); if (i == 1) return 1+total; return recur_tail(i-1, total +i); }
时间: 2024-10-14 04:52:21