本文首發于我的個人部落格: 尾尾部落
題目描述
求1+2+3+...+n,要求不能使用乘除法、for、while、if、else、switch、case等關鍵字及條件判斷語句(A?B:C)。
解題思路
累加不能用循環的話,那就試試遞歸吧。
判斷遞歸的終止條件不能用 if 和 switch,那就用短路與代替。
(n > 0) && (sum += Sum_Solution(n-1))>0
隻有滿足n > 0的條件,
&&
後面的表達式才會執行。
參考代碼
public class Solution {
public int Sum_Solution(int n) {
int sum = n;
boolean t = (n > 0) && (sum += Sum_Solution(n-1))>0;
return sum;
}
}