求1+2+3+…+n
题目描述
求1+2+3+…+n,要求不能使用乘除法、for、while、if、else、switch、case等关键字及条件判断语句(A?B:C)。
思路:使用递归f(n) = f(n-1) + n, 但是不能使用if进行递归出口的控制,因此利用python中and的属性,即and判断都为真的话输出and后面的那个数字。
正确答案:
# -*- coding:utf-8 -*-
class Solution:
def Sum_Solution(self, n):
# write code here
ans = n>0 and n
return ans and ans + self.Sum_Solution(n-1)
或
# -*- coding:utf-8 -*-
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):
# write code here
ans = n>0 and n
return ans + self.Sum_Solution(n-1)
错误原因:在return的时候,如果不给定递归的结束条件,递归将无穷尽地计算下去,在本题中,将ans and ans + self.Sum_Solution(n-1)作为递归的终止条件,即当n==0时,return 0,结束递归。