剑指offer 面试64题

题目: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)

 

posted @ 2018-06-03 23:31  Fintech带你飞  阅读(987)  评论(0编辑  收藏  举报