牛客-剑指offer系列题解:求1+2+3+...+n

记录刷题的过程。牛客和力扣中都有相关题目,这里以牛客的题目描述为主。该系列默认采用python语言。
1、问题描述:
求1+2+3+…+n,要求不能使用乘除法、for、while、if、else、switch、case等关键字及条件判断语句(A?B:C)。

2、数据结构:
递归

3、题解:
方法1:
在这里插入图片描述

# -*- coding:utf-8 -*-
class Solution:
    def __init__(self):
        self.res = 0
    def Sum_Solution(self, n):
        # write code here
        n > 1 and self.Sum_Solution(n - 1)
        self.res += n
        return self.res

下面提供两种方法,但是用了此题的限制,只作为开阔一下思路用,不作为满足此题的题解。
方法2:平均计算

# -*- coding:utf-8 -*-
class Solution:
    def Sum_Solution(self, n):
        # write code here
        return n * (n + 1) // 2

方法3:迭代

# -*- coding:utf-8 -*-
class Solution:
    def Sum_Solution(self, n):
        # write code here
        res = 0
        for i in range(1,n + 1):
            res += i
        return res

4、复杂度分析:
方法1:
时间复杂度都为O(N)
空间复杂度都为O(N)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值