题目描述
求1+2+3+…+n,要求不能使用乘除法、for、while、if、else、switch、case等关键字及条件判断语句(A?B:C)。
题目要求
时间限制:1秒 空间限制:32768K
解题思路: 利用逻辑与(&&)的短路实现递归出口,如果 n == 0 ,(n>0) && ((temp += Sum_Solution(n-1))>0);执行前面的判断,flag为false,直接返回0;如果 n > 0 ,(n>0) && ((temp += Sum_Solution(n-1))>0);执行后面的语句,实现递归计算。
public class Solution {
public int Sum_Solution(int n) {
int temp = n;
boolean flag = (n>0) && ((temp += Sum_Solution(n-1))>0);
return temp;
}
}