首页 > 解决方案 > 如何在 Python3 中修复我的“添加函数使用按位运算符”代码?

问题描述

我想在 Python 中用按位运算符编写一个“add”函数,但在尝试计算“5 + (-3)”或“(-4) + 8”时遇到了一个错误。

我的 Python 版本是 3.7。

def bitwiseplus(x, y):
    while y:
        ans = x ^ y
        y = (x & y) << 1
        x = ans
    return ans

执行 bitwiseplus(5, -3) 或 bitwiseplus(-4, 8) 时会超时。

标签: pythonaddbitwise-operators

解决方案


def bitwiseplus(x, y):
    s, c, i = x ^ y, x & y, 1
    # Max number of bits in the final answer
    N = max(x.bit_length(), y.bit_length()) + 2
    while i < N:
        s, c, i = s ^ (c << 1), s & (c << 1), i + 1
    # An overflow is detected if we have x carry out of the final addition
    # If so, the sum should be zero.
    if c ^ (1 << (N - 1)) == 0:
        return 0

    # If the final answer is positive (we check if MSB of answer is 0)
    # then keep only lower N bits of answer. This is needed since we abort
    # the ripple addition above once we know we have calculated enough bits
    if not (s >> (N - 1)) & 1:
        # ~(~0 << N) will generate 'N' ones with leading zeros.
        # For example N=3 gives 0xb00111
        s = s & ~(~0 << N)
    return s

print (bitwiseplus(5,-3))

输出:

2

推荐阅读