题目:64题

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

 

解法一:利用Python特性

1 # -*- coding:utf-8 -*-
2 class Solution:
3     def Sum_Solution(self, n):
4         # write code here
5         return sum(list(range(1,n+1)))

解法二:利用两个函数,一个函数充当递归函数的角色,另一个函数处理终止递归的情况,如果对n连续进行两次反运算,那么非零的n转换为True,0转换为False。利用这一特性终止递归。注意考虑测试用例为0的情况,参考自GitHub

# -*- coding:utf-8 -*-
class Solution:
    def Sum_Solution(self, n):
        # write code here     
        return self.sum(n)
    
    def sum0(self,n):
        return 0
    
    def sum(self,n):
        func={False:self.sum0,True:self.sum}
        return n+func[not not n](n-1)

解法三:终止递归采用逻辑与的短路特性,如下:

# -*- coding:utf-8 -*-
class Solution:
    def Sum_Solution(self, n):
        # write code here     
        return n and n + self.Sum_Solution(n-1)

 

相关文章:

  • 2021-12-13
  • 2022-02-26
  • 2021-09-06
  • 2021-12-23
  • 2021-09-20
  • 2021-09-29
  • 2021-09-21
  • 2022-01-25
猜你喜欢
  • 2022-01-13
  • 2021-07-23
  • 2021-09-13
  • 2021-11-03
  • 2021-09-20
  • 2021-07-09
相关资源
相似解决方案