comments: true
difficulty: 中等
edit_url: https://github.com/doocs/leetcode/edit/main/lcof/面试题64. 求1%2B2%2B…%2Bn/README.md
面试题 64. 求 1+2+...+n
题目描述
求 1+2+...+n
,要求不能使用乘除法、for、while、if、else、switch、case等关键字及条件判断语句(A?B:C)。
示例 1:
输入: n = 3
输出: 6
示例 2:
输入: n = 9
输出: 45
限制:
1 <= n <= 10000
解法
方法一
Python3
python
class Solution:
def sumNums(self, n: int) -> int:
# n 是 0,所以 0 and (0 + self.sumNums(-1)) 结果是 0
return n and (n + self.sumNums(n - 1))
Java
java
class Solution {
public int sumNums(int n) {
int s = n;
boolean t = n > 0 && (s += sumNums(n - 1)) > 0;
return s;
}
}
C++
cpp
class Solution {
public:
int sumNums(int n) {
n && (n += sumNums(n - 1));
return n;
}
};
Go
go
func sumNums(n int) int {
s := 0
var sum func(int) bool
sum = func(n int) bool {
s += n
return n > 0 && sum(n-1)
}
sum(n)
return s
}
TypeScript
ts
var sumNums = function (n: number): number {
return n && n + sumNums(n - 1);
};
Rust
rust
impl Solution {
pub fn sum_nums(mut n: i32) -> i32 {
n != 0
&& (
{
n += Solution::sum_nums(n - 1);
},
true,
)
.1;
n
}
}
JavaScript
js
/**
* @param {number} n
* @return {number}
*/
var sumNums = function (n) {
return (n ** 2 + n) >> 1;
};
C#
cs
public class Solution {
public int result;
public int SumNums(int n) {
helper(n);
return result;
}
public bool helper(int n) {
result += n;
return n == 0 || helper(n - 1);
}
}
Swift
swift
class Solution {
func sumNums(_ n: Int) -> Int {
var s = n
let _ = n > 0 && { s += sumNums(n - 1); return true }()
return s
}
}