1. 问题描述
求1+2+3+...+n,要求不能使用乘除法、for、while、if、else、switch、case等关键字及条件判断语句(A?B:C)。
2. 可以使用公式方法 1 + 2 + 3 + ... + n = (n + 1)n / 2
public class Solution {
public int Sum_Solution(int n) {
int sum = (int) (Math.pow(n,2) + n);
return sum>>1;
}
}
3. 这是一道很简单的题,但是不能用到循环和判断,所以只能考虑递归加短路
public class Solution {
public int Sum_Solution(int n) {
int res = n;
boolean flag = (n>0)&&((res+=Sum_Solution(n-1))>0);
return res;
}
}