cubegao

Swift.求1+2+...+n

2015-07-06

题目描述:求1+2+3+…+n,要求不能使用乘除法、for、while、if、else、switch、case等关键字及条件判断语句(A?B:C)。

1
2
3
4
5
6
7
8
9
10
import Foundation

class For46Solution {
func addSum(_ num: Int) -> Int {

var res = 0
num>0 && (res = num + addSum(num - 1)) == ()
return res
}
}

算法思想:累加不能用循环的话,那就试试递归吧。

github地址:https://github.com/cubegao/LeetCode

Tags: 算法

扫描二维码,分享此文章