求1+2+3+...+n

求1+2+3+...+n

http://www.nowcoder.com/questionTerminal/7a0da8fc483247ff8800059e12d7caf1

一行代码简便解法,直接递归短路代替if语句,当n为0或者负数时,自动忽略之后的递归

# -*- coding:utf-8 -*-
class Solution:
    def Sum_Solution(self, n):
        # write code here
        return n and ( n + self.Sum_Solution(n-1) )
全部评论
要求空间复杂度o(1),你这递归用栈直接超了啊
点赞 回复
分享
发布于 2022-01-21 19:40

相关推荐

投递美团等公司10个岗位
点赞 评论 收藏
转发
24 收藏 评论
分享
牛客网
牛客企业服务