LeetCode-offer64: Seeking 1+2+…+n

Claim

Seek 1+2+…+n. It is required that keywords such as multiplication and division, for, while, if, else, switch, case and conditional judgment statements (A?B:C) cannot be used.

Example 1:
Input: n = 3
Output: 6

Example 2:
Input: n = 9
Output: 45

analysis

The title clearly states that we cannot use multiplication and division, loops, and conditional judgments. But we can implement loop and condition judgment equivalently by other methods. Such as using recursion instead of loop.
But recursion requires an end sign, and obviously if is disabled, we are here to consider the short-circuit nature of logic statements and the clever combination of recursion. The specific code is as follows:

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

Guess you like

Origin blog.csdn.net/weixin_43745087/article/details/113885314