求1+2+3+...+n,要求不能使用乘除法、for、while、if、else、switch、case等关键字及条件判断语句(A?B:C)。
思路
第一种做法
用公式
n(n-1)/2= n^2 + n
pow是平方的意思
public class Solution {
public int Sum_Solution(int n) {
// n(n-1)/ 2 = n^2 + n
int num = (int)(Math.pow(n,2) + n);
return num >> 1;
}
}
第二种做法
递归
如果n小于0,直接返回
黑色的箭头是调用,黄色的箭头是返回
public class Solution {
public int Sum_Solution(int n) {
int ans = n;
boolean flag = (n > 0) && ((ans += Sum_Solution(n-1)) > 0);
return ans;
}
}