题目描述
求1+2+…+n,要求不能使用乘除法、for、while、if、else、switch、case等关键字及条件判断语句(A?B:C)。
解题思路
短路逻辑+递归
- 当n大于0时,由于and运算符的短路逻辑,return n+self.Sum_Solution(n-1);
- 而n = 0时,return n.
class Solution:
def Sum_Solution(self, n):
# write code here
return n and n + self.Sum_Solution(n-1)