comments | difficulty | edit_url |
---|---|---|
true |
中等 |
求 1+2+...+n
,要求不能使用乘除法、for、while、if、else、switch、case等关键字及条件判断语句(A?B:C)。
示例 1:
输入: n = 3 输出: 6
示例 2:
输入: n = 9 输出: 45
限制:
1 <= n <= 10000
class Solution:
def sumNums(self, n: int) -> int:
return n and (n + self.sumNums(n - 1))
class Solution {
public int sumNums(int n) {
int s = n;
boolean t = n > 0 && (s += sumNums(n - 1)) > 0;
return s;
}
}
class Solution {
public:
int sumNums(int n) {
n && (n += sumNums(n - 1));
return n;
}
};
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
}
var sumNums = function (n: number): number {
return n && n + sumNums(n - 1);
};
impl Solution {
pub fn sum_nums(mut n: i32) -> i32 {
n != 0
&& (
{
n += Solution::sum_nums(n - 1);
},
true,
)
.1;
n
}
}
/**
* @param {number} n
* @return {number}
*/
var sumNums = function (n) {
return (n ** 2 + n) >> 1;
};
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);
}
}
class Solution {
func sumNums(_ n: Int) -> Int {
var s = n
let _ = n > 0 && { s += sumNums(n - 1); return true }()
return s
}
}