Как исправить мой код "добавить функцию использовать побитовый оператор" в Python3? - PullRequest
2 голосов
/ 20 мая 2019

Я хочу написать «добавить» функцию с побитовым оператором в Python, но встретил ошибку при попытке вычислить «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), время истекает.

1 Ответ

0 голосов
/ 20 мая 2019
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
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...