求1+2+3+...+n的和不能使用乘除、for等(思路与实现)

题目描述

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

思路:

使用短路的方法&&。当n = 0的时候发生短路。

实现:

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

猜你喜欢

转载自blog.csdn.net/qq_28081081/article/details/80871424