题目信息

  • 题目;剑指 Offer 64. 求1+2+…+n

  • 时间: 2020-08-05

  • 题目链接:Leetcode

  • tag:位运算 限制运算符号

  • 难易程度:中等

  • 题目描述:

    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
1. 1 <= n <= 10000

解题思路

本题难点

不能使用乘除法、for、while、if、else、switch、case等关键字及条件判断语句

具体思路

逻辑运算符:

  • if(A && B) // 若 A 为 false ,则 B 的判断不会执行(即短路),直接判定 A && B 为 false
  • if(A || B) // 若 A 为 true ,则 B 的判断不会执行(即短路),直接判定 A || B 为 true

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

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

提示

代码

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

复杂度分析:

  • 时间复杂度 O(N) : 计算 n+(n−1)+…+2+1n+(n−1)+…+2+1 需要开启 n 个递归函数。
  • 空间复杂度 O(N) : 递归深度达到 n,系统使用 O(n)大小的额外空间。

其他优秀解答

解题思路

平均计算、迭代、递归

代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
public int sumNums(int n) {
return (1 + n) * n / 2;
}

public int sumNums(int n) {
int res = 0;
for(int i = 1; i <= n; i++)
res += i;
return res;
}

public int sumNums(int n) {
if(n == 1) return 1;
n += sumNums(n - 1);
return n;
}