题目:求 1+2+...+n
,要求不能使用乘除法、for、while、if、else、switch、case等关键字及条件判断语句(A?B:C)。
思路:巧用python逻辑运算符“and”。x and y ,如果 x 为 False,x and y 返回 False,否则它返回 y 的计算值。
class Solution:
def sumNums(self, n: int) -> int:
return n != 0 and n + self.sumNums(n-1)
if __name__ == "__main__":
sol = Solution()
res = sol.sumNums(8)