LeetCode 剑指 Offer 64. 求1+2+…+n

原题链接

短路效应的应用

本题使用递归结构,一般递归结束条件为:

	if(n <= 1) return 1;

这里可以换成 等价的布尔判断,当 n > 1 的条件 不满足时候,递归此时自动返回,返回层执行return 。

本题代码:

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

猜你喜欢

转载自blog.csdn.net/qq_43078427/article/details/114283363