短路效应的应用
本题使用递归结构,一般递归结束条件为:
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;
}
};