剑指Offer47:求1+2+3+...+n(java)

参考牛客“nailperry”的解答:https://www.nowcoder.com/questionTerminal/7a0da8fc483247ff8800059e12d7caf1?f=discussion

思路分析:

利用逻辑与的短路特性实现递归终止。&&短路的功能,即如果第一个表达式为false,则不再计算第二个表达式
当递归到0时,boolean a=(n>0)&&((res+= Sum_Solution(n-1))>0);n不大于0,逻辑与不进行后面的Sum_Solution(n-1)递归,最终向上一层返回0,结束。

题目描述

求1+2+3+...+n,要求不能使用乘除法、for、while、if、else、switch、case等关键字及条件判断语句(A?B:C)。

Java代码:

public class Solution {
    public int Sum_Solution(int n) {
        int res=n;
        boolean a=(n>0)&&((res+= Sum_Solution(n-1))>0);
        return res;
    }
}

猜你喜欢

转载自www.cnblogs.com/dongmm031/p/12275510.html
今日推荐