python--剑指offer--中等--64. 求1+2+…+n

本文介绍了一种使用Python实现从1累加到n的递归算法,并通过巧妙运用位运算符来减少代码量,同时深入探讨了如何利用逻辑运算符替代传统if...elif...else...结构的方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

class Solution:
    def sumNums(self, n: int) -> int:
        n = n and n + self.sumNums(n - 1)
        return n


if __name__ == '__main__':
    solution = Solution()
    res = solution.sumNums(3)
    print(res)

在这里插入图片描述
在这里插入图片描述

class Solution:
    def sumNums(self, n: int) -> int:
        ans, a, b = 0, n, n + 1
        # 0
        ans = (not b & 1 and ans) or (b & 1 and ans + a)
        b >>= 1
        a <<= 1
        # 1
        ans = (not b & 1 and ans) or (b & 1 and ans + a)
        b >>= 1
        a <<= 1
        # 2
        ans = (not b & 1 and ans) or (b & 1 and ans + a)
        b >>= 1
        a <<= 1
        # 3
        ans = (not b & 1 and ans) or (b & 1 and ans + a)
        b >>= 1
        a <<= 1
        # 4
        ans = (not b & 1 and ans) or (b & 1 and ans + a)
        b >>= 1
        a <<= 1
        # 5
        ans = (not b & 1 and ans) or (b & 1 and ans + a)
        b >>= 1
        a <<= 1
        # 6
        ans = (not b & 1 and ans) or (b & 1 and ans + a)
        b >>= 1
        a <<= 1
        # 7
        ans = (not b & 1 and ans) or (b & 1 and ans + a)
        b >>= 1
        a <<= 1
        # 8
        ans = (not b & 1 and ans) or (b & 1 and ans + a)
        b >>= 1
        a <<= 1
        # 9
        ans = (not b & 1 and ans) or (b & 1 and ans + a)
        b >>= 1
        a <<= 1
        # 10
        ans = (not b & 1 and ans) or (b & 1 and ans + a)
        b >>= 1
        a <<= 1
        # 11
        ans = (not b & 1 and ans) or (b & 1 and ans + a)
        b >>= 1
        a <<= 1
        # 12
        ans = (not b & 1 and ans) or (b & 1 and ans + a)
        b >>= 1
        a <<= 1
        # 13
        ans = (not b & 1 and ans) or (b & 1 and ans + a)
        return ans >> 1


if __name__ == '__main__':
    solution = Solution()
    res = solution.sumNums(5)
    print(res)

在这里插入图片描述
补充:

(1) 本题的难点在于对于运算符的使用

  • 对于if...elif...elif..., 使用or连接多种情况,使用and连接每一种情况的条件和执行体,最后对每一个条件进行斟酌。如
    ans = (not b & 1 and ans) or (b & 1 and ans + a)
    
    相当于
    if not b & 1:
    	ans = ans
    elif not b& 1:
    	ans = ans + a
    

(2) python中没有xor逻辑运算符,只有xor位运算符"^"。但逻辑运算符有个等式:

  • a⊕b = (¬a ∧ b) ∨ (a ∧¬b)

[参考博客]
求1+2+…+n

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值