求1+2+3+...+n—要求不能使用乘除法、循环、判断等关键字

题目描述
求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;
    }
}

猜你喜欢

转载自blog.csdn.net/ly52014/article/details/89891886