题目描述
求1+2+3+...+n,要求不能使用乘除法、for、while、if、else、switch、case等关键字及条件判断语句(A?B:C)。
思路
- 先用一个变量去保存当前值
- 利用n>0和递归,从n遍历到0
- 从0开始往回返,每次加上进来保存的当前值
# -*- coding:utf-8 -*-
class Solution:
def Sum_Solution(self, n):
# write code here
res=n
temp=n>0 and self.Sum_Solution(n-1)
res+=temp
return res
测试用例
if __name__=='__main__':
s=Solution()
n=3
print(s.Sum_Solution(n))