求1+2+3+...+n,要求不能使用乘除法、for、while、if、else、switch、case等关键字及条件判断语句(A?B:C)。
数据范围: ![](https://www.nowcoder.com/equation?tex=0%20%3C%20n%20%5Cle%20200%20)
进阶: 空间复杂度
,时间复杂度 ![](https://www.nowcoder.com/equation?tex=O(n))
进阶: 空间复杂度
# -*- coding:utf-8 -*- class Solution: def Sum_Solution(self, n): # write code here def f(x,y): return x+y return reduce(f, range(1,n+1))方2:利用sum和range
# -*- coding:utf-8 -*- class Solution: def Sum_Solution(self, n): # write code here return sum(range(1,n+1))
# -*- coding:utf-8 -*- class Solution: def Sum_Solution(self, n): # write code here return sum(range(1,n+1))
class Solution: def Sum_Solution(self, n): # write code here return n>0 and self.Sum_Solution(n-1)+n
# -*- coding:utf-8 -*- class Solution: def Sum_Solution(self, n): # write code here return sum(range(n+1))
class Solution: def Sum_Solution(self, n): # write code here return n and n+self.Sum_Solution(n-1)
# -*- coding:utf-8 -*- class Solution: def Sum_Solution(self, n): return n != 0 and n + self.Sum_Solution((n-1))
class Solution: def Sum_Solution(self, n): return n and n + self.Sum_Solution(n - 1)
# -*- coding:utf-8 -*- class Solution: def Sum_Solution(self, n): return n and n + self.Sum_Solution(n-1) s = Solution() ans = s.Sum_Solution(10) print(ans)
# -*- coding:utf-8 -*- # 解题思路:非递归方法,使用内置函数和位运算 class Solution: def Sum_Solution(self, n): # write code here return (pow(n, 2) + n) >> 1 # 递归方法 class Solution: def __init__(self): self.sum = 0 def Sum_Solution(self, n): # write code here def qiuhe(): self.sum += n n > 0 and self.Sum_Solution(n-1) qiuhe() return self.sum
# -*- coding:utf-8 -*- class Solution: def Sum_Solution(self, n): #利用短路原理 self.sum = 0 def loop(n): self.sum += n #递归停止条件由n决定 #当n>0时,左侧为True,执行右侧并返回 #当n==0时,左侧为False,由于and与操作只要有一个False结果即为False,那么右侧结果无需执行,直接返回 return n and loop(n-1) loop(n) return self.sum
# -*- coding:utf-8 -*- class Solution: def Sum_Solution(self, n): # write code here return sum(range(n+1))