剑指offer题解--③求1+2+3+...+n

求1+2+3+...+n

https://www.nowcoder.com/practice/7a0da8fc483247ff8800059e12d7caf1?tpId=13&&tqId=11200&rp=1&ru=/ta/coding-interviews&qru=/ta/coding-interviews/question-ranking

题目描述

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

解题思路

利用java短路与&&,以及递归的思想,来求累加;

代码演示

    public static int Sum_Solution(int n) {
        int sum = n;
        boolean a = (n > 0) &&( (sum+=Sum_Solution(n-1)) > 0 );
        return sum;
    }
全部评论

相关推荐

投递恒生电子股份有限公司等公司10个岗位
点赞 评论 收藏
转发
点赞 收藏 评论
分享
牛客网
牛客企业服务