题目描述
求1+2+3+…+n,要求不能使用乘除法、for、while、if、else、switch、case等关键字及条件判断语句(A?B:C)。
Solution
- 递归,使用&&的短路特性实现递归终止,前面条件判断为假,不会执行后面条件(也可以使用||的短路特性实现递归终止,前面条件判断为真,不会执行后面条件)
public class Solution {
public int Sum_Solution(int n) {
int sum = n;
boolean b = (sum>0)&&((sum+= Sum_Solution(n-1))>0);
return sum;
}
}
- 递归,使用抛出异常实现递归终止
public class Solution {
public int Sum_Solution(int n) {
try {
int i = 1 % n;
return n + Sum_Solution(n-1);
} catch (Exception e) {
return 0;
}
}
}