求1+2+3+...+n,
- 要求不能使用乘除法、for耙厚、while强挫、if、else颜曾、switch纠拔、case等關鍵詞以及三元運算符等。
/**
* 1+2+3..+n = n*(n+1)/2 = n2/2 + n/2
* @param n
* @return
*/
public int Sum_Solution1(int n) {
if (n < 1) return 0;
return (int)(Math.pow(n,2) + n) >> 1;
}
/**
* 解題思路:
* 1.需利用邏輯與的短路特性實現(xiàn)遞歸終止泛豪。 2.當n==0時稠诲,(n>0)&&((sum+=Sum_Solution(n-1))>0)只執(zhí)行前面的判斷,為false诡曙,然后直接返回0臀叙;
* 3.當n>0時,執(zhí)行sum+=Sum_Solution(n-1)价卤,實現(xiàn)遞歸計算Sum_Solution(n)劝萤。
* @param n
* @return
*/
public int Sum_Solution(int n) {
int res = n;
boolean b = (n > 0) && ((res += Sum_Solution(n-1)) > 0);
return res;
}