时间: 2019-07-06
题目链接:Leetcode
tag:位运算 限制运算符号
难易程度:中等
题目描述:
求 1+2+...+n
,要求不能使用乘除法、for、while、if、else、switch、case等关键字及条件判断语句(A?B:C)。
示例1:
输入: n = 3
输出: 6
示例2:
输入: n = 9
输出: 45
注意
1. 1 <= n <= 10000
本题难点
不能使用乘除法、for、while、if、else、switch、case等关键字及条件判断语句
具体思路
逻辑运算符:
本题需要实现 “当 n=1 时终止递归” 的需求,可通过短路效应实现
n > 1 && sumNums(n - 1) // 当 n = 1 时 n > 1 不成立 ,此时 “短路” ,终止后续递归
提示
class Solution {
int res = 0;
public int sumNums(int n) {
boolean flag = n > 1 && sumNums(n-1)>0;
res += n;
return res;
}
}
复杂度分析:
解题思路
平均计算、迭代、递归
代码
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;
}
原文:https://www.cnblogs.com/ID-Wangqiang/p/13288126.html