Seeking 1 + 2 + 3 + ... .. + n

[Problem] seeking 1 + 2 + 3 + ... + n, requires multiplication and division can not be used, for, while, if, else, switch, case and keywords such as conditional statement (A B:? C).

[Thinking] Since the operator can not use a lot of topics, we think only method using recursion, but recursion to determine the general recursive end condition, but the problem did not allow the use of an if statement, so we can use the && operator, is this sentence : res && (res + = Sum_Solution (n-1)), i.e. when the zero res, and the right operator will not be performed, thus ending the recursive return res to obtain the final sum, great idea!

class Solution {
public:
    int Sum_Solution(int n) {
        int res = n;
        res && (res += Sum_Solution(n-1));
        return res;
    }
};

Guess you like

Origin www.cnblogs.com/zhudingtop/p/11404101.html