剑指offer47_求1+2+3+...+n_题解

求1+2+3+...+n

题目描述

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

示例1

输入

5

返回值

15

分析

方案一:递归+短路效应

本题需要实现 “当 n = 1 时终止递归” 的需求,可通过短路效应实现。

n > 1 && sumNums(n - 1) // 当 n = 1 时 n > 1 不成立 ,此时 “短路” ,终止后续递归

代码1

/**
1.时间复杂度 O(n): 计算 n + (n-1) + ... + 2 + 1 需要开启 n 个递归函数。
2.空间复杂度 O(n): 递归深度达到 n ,系统使用 O(n) 大小的额外空间。
**/
class Solution
{
public:
    int res = 0;
    int Sum_Solution(int n)
    {
        bool x = n > 1 && Sum_Solution(n - 1);
        res += n;
        return res;
    }
};

代码2

class Solution
{
public:
    int Sum_Solution(int n)
    {
        bool x = n > 1 && (n += Sum_Solution(n - 1)); // 为构成语句,增加一个辅助变量x
        return n;
    }
};

posted @ 2021-01-23 11:27  RiverCold  阅读(26)  评论(0编辑  收藏  举报