求 1 + 2 + 3 + ... + n,要求不能使用乘除法、for、while、if、else、switch、case 等關(guān)鍵字及條件判斷語句 A ? B : C
解題思路
需要利用邏輯與的短路特性來實(shí)現(xiàn)遞歸的終止,當(dāng) n == 0 時,(n > 0) && ((sum += Sum_Solution(n - 1)) > 0) 只執(zhí)行前面的判斷,為 false,然后直接返回 0;當(dāng) n > 0 時,執(zhí)行 sum += Sum_Solution(n - 1),實(shí)現(xiàn)遞歸計(jì)算 Sum_Solution(n)
public class Solution {
public int Sum_Solution(int n) {
int sum = n;
boolean flag = (n > 0) && (sum += Sum_Solution(n - 1)) > 0;
return sum;
}
}
|