剑指offer64 求1+2+3+...+n 【递归】

题目描述

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

示例 1:

1
2
输入: n = 3
输出: 6

示例 2:

1
2
输入: n = 9
输出: 45

限制:

  • 1 <= n <= 10000

解题思路

方法一:递归

使用递归方法,利用&&逻辑运算符来坐终止条件,例如A&&B,当A为true时,才进行B操作,如果A为false则不进行操作。

代码实现

1
2
3
4
5
6
class Solution {
public int sumNums(int n) {
boolean flag = n > 0 && (n += sumNums(n - 1)) > 0;
return n;
}
}

复杂度分析

时间复杂度:O(n)

空间复杂度:O(n)

资料

剑指offer64 求1+2+3+...+n 【递归】

http://example.com/2021/06/06/剑指offer64-求1-2-3-n/

Author

John Doe

Posted on

2021-06-06

Updated on

2021-06-08

Licensed under

You need to set install_url to use ShareThis. Please set it in _config.yml.
You forgot to set the business or currency_code for Paypal. Please set it in _config.yml.

Comments

You forgot to set the shortname for Disqus. Please set it in _config.yml.