剑指 Offer 64. 求1+2+…+n
作者:互联网
思路:参考K神方法,利用逻辑运算符的短路效应
首先看迭代的方法:
class Solution {
public:
int sumNums(int n) {
if(n == 1) return 1;
n += sumNums(n-1);
return n;
}
};
由于题目中要求不能用if
class Solution {
int res = 0;
public:
int sumNums(int n) {
bool flag = (n > 1) && sumNums(n-1) > 0;
res+=n;
return res;
}
};
标签:return,Offer,int,res,sumNums,Solution,64,public 来源: https://blog.csdn.net/qq_41295976/article/details/118874069