剑指offer 72- 求1+2+…+n

2021-06-09  本文已影响0人  顾子豪

求 1+2+…+n,要求不能使用乘除法、for、while、if、else、switch、case 等关键字及条件判断语句 (A?B:C)

样例

输入:10

输出:55

分析:
考察短路与的应用

最直接的想法就是用递归,sum(n) = n+sum(n-1),但是要注意终止条件,由于求的是1+2+…+n的和,所以需要在n=0的时候跳出递归,但是题目要求不能使用if,while等分支判断,可以考虑利用&&短路运算来终止判断。

时间复杂度:O(N)

class Solution {
public:
    int getSum(int n) {
        /*int res = n;
        if(n>0) res+=getSum(n-1);
        return res;*/
        
        int res = n;
        // if(n>0) res+=getSum(n-1);
        n>0 && (res+=getSum(n-1));
        return res;
    }
};
上一篇 下一篇

猜你喜欢

热点阅读