剑指Offer(Python多种思路实现):求1+2+···+n
题目:64题
求1+2+3+...+n,要求不能使用乘除法、for、while、if、else、switch、case等关键字及条件判断语句(A?B:C)。
解题思路一:python方法
def Sum_Solution(self, n):
return n and (n+self.Sum_Solution(n-1))
解题思路二:
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)
本文探讨了剑指Offer中的一道难题,即如何在不使用常见控制结构的情况下计算1到n的累加和。提供了两种创新的Python实现方案,包括递归调用和元编程技巧。

1万+

被折叠的 条评论
为什么被折叠?



