LeetCode Sword refers to Offer 64. Find 1+2+…+n

Original title link

Application of short-circuit effect

This question uses a recursive structure, and the general recursive end conditions are:

	if(n <= 1) return 1;

This can be replaced with an equivalent Boolean judgment. When the condition of n> 1 is not met, the recursion will automatically return at this time, and the return layer will execute return.

The code of this question:

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

Guess you like

Origin blog.csdn.net/qq_43078427/article/details/114283363