求 1+2+...+n ,要求不能使用乘除法、for、while、if、else、switch、case等关键字及条件判断语句(A?B:C)。
示例 1:
输入: n = 3
输出: 6
示例 2:
输入: n = 9
输出: 45
限制:
1 <= n <= 10000 分析:
方法:短路
既然不能使用乘除法,那只能使用加法,但是又不能使用循环,迭代肯定不行,递归需要终止条件,终止条件需要条件判断语句,那么有没什么可以代替条件判断语句的?Java 的 与运算 和 或运算 有着 短路 功能,与运算前面为假时不进行后面判断,或运算前面为真时不进行后面判断,利用这个特性我们可以用来终止递归。
时间复杂度:O(n)
空间复杂度:O(n)
class Solution {
//定义结果
int sum = 0;
public int sumNums(int n) {
recur(n);
return sum;
}
//递归加值
public boolean recur(int n){
//加值
sum += n;
//n != 1 时会短路,不进行后面递归
return n == 1 || recur(n-1);
}
}
题目来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/qiu-12n-lcof



