Skip to content

Latest commit

 

History

History
167 lines (127 loc) · 2.5 KB

File metadata and controls

167 lines (127 loc) · 2.5 KB
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

解法

方法一

Python3

class Solution:
    def sumNums(self, n: int) -> int:
        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
    }
}