跳转至

面试题 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

解法

方法一

1
2
3
class Solution:
    def sumNums(self, n: int) -> int:
        return n and (n + self.sumNums(n - 1))
1
2
3
4
5
6
7
class Solution {
    public int sumNums(int n) {
        int s = n;
        boolean t = n > 0 && (s += sumNums(n - 1)) > 0;
        return s;
    }
}
1
2
3
4
5
6
7
class Solution {
public:
    int sumNums(int n) {
        n && (n += sumNums(n - 1));
        return n;
    }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
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
}
1
2
3
var sumNums = function (n: number): number {
    return n && n + sumNums(n - 1);
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
impl Solution {
    pub fn sum_nums(mut n: i32) -> i32 {
        n != 0
            && (
                {
                    n += Solution::sum_nums(n - 1);
                },
                true,
            )
                .1;
        n
    }
}
1
2
3
4
5
6
7
/**
 * @param {number} n
 * @return {number}
 */
var sumNums = function (n) {
    return (n ** 2 + n) >> 1;
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
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);
    }
}
1
2
3
4
5
6
7
class Solution {
    func sumNums(_ n: Int) -> Int {
        var s = n
        let _ = n > 0 && { s += sumNums(n - 1); return true }()
        return s
    }
}

评论