64. 求 1+2+…+n
comments: true
difficulty: 中等
edit_url: https://github.com/doocs/leetcode/edit/main/lcof/%E9%9D%A2%E8%AF%95%E9%A2%9864.%20%E6%B1%821%2B2%2B%E2%80%A6%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
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
class Solution {
public int sumNums(int n) {
int s = n;
boolean t = n > 0 && (s += sumNums(n - 1)) > 0;
return s;
}
}
C++
class Solution {
public:
int sumNums(int n) {
n && (n += sumNums(n - 1));
return n;
}
};
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
var sumNums = function (n: number): number {
return n && n + sumNums(n - 1);
};
Rust
impl Solution {
pub fn sum_nums(mut n: i32) -> i32 {
n != 0
&& (
{
n += Solution::sum_nums(n - 1);
},
true,
)
.1;
n
}
}
JavaScript
/**
* @param {number} n
* @return {number}
*/
var sumNums = function (n) {
return (n ** 2 + n) >> 1;
};
C#
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
class Solution {
func sumNums(_ n: Int) -> Int {
var s = n
let _ = n > 0 && { s += sumNums(n - 1); return true }()
return s
}
}