求1+2+3+…+n,要求不能使用乘除法、for、while、if、else、switch、case等关键字及条件判断语句(A?B:C)。
思路
考研发散思维和知识面的宽度,以及对编程技术理解的深度
1.。。n的和除了用公式n(n+1)/2,无外乎循环和递归两种思路
- 循环,要用for 、while
- 递归 要有判断条件if
都不行
用 && 短路
需利用逻辑与的短路特性实现递归终止。 2.当n==0时,(n>0)&&((sum+=Sum_Solution(n-1))>0)只执行前面的判断,为false,然后直接返回0;
public class Solution {
public int Sum_Solution(int n) {
int ans = n;
boolean s = (ans >0)&& ((ans += Sum_Solution(n-1))>0);
return ans;
}
}
时O(n)
利用Math实现 n(n+1)
public class Solution {
public int Sum_Solution(int n) {
return (int)(Math.pow(n,2)+n)>>1;
}
}