gpt4 book ai didi

python - 如何在使用按位运算添加两个整数时添加无限循环的代码修复

转载 作者:行者123 更新时间:2023-11-30 22:48:18 26 4
gpt4 key购买 nike

这是原文question .

以下是使用按位运算将两个整数相加的代码:

def getSum(self, a, b):

while (a & b):
x = a & b
y = a ^ b
a = x << 1
b = y

return a ^ b

虽然我知道它在添加正整数和负整数时进入无限循环的原因,但我需要一些帮助来为此提供代码修复。

最佳答案

我假设您已经了解了无限循环背后的逻辑。 logic

以下是您的程序的行为:

1. Gives correct result when both a and b are positive.

2. Gives correct result when both a and b are negative.

3. Gives correct result when one of them is positive and one of them is negative
and positive one is smaller than negative one.

4. Gives incorrect result (infinite loop) when one of them is positive and one of
them is negative and positive one is bigger than negative one.`

因此您必须明确处理第四种情况。您可以为其编写一个包装器。此外,您还需要一个实用程序来对数字的值取反,即,如果数字为正数,则将其变为负数,反之亦然:

# I will leave neagte(x) on you to implement.
# So assume we have negate() method available.

def getSum(a,b):
# if a is -ve and b is +ve and abs(a) is less than b.
cond1 = a < 0 and b > 0 and abs(a) < b

# if b is -ve and a is +ve and abs(b) is less than a.
cond2 = b < 0 and a > 0 and abs(b) < a

# if any of these conditions are met. negate the value of a and b
# and negate the value of answer as well.
if cond1 or cond2:
return negate(_getSum(negate(a),negate(b)))

# otherwise run normally.
return _getSum(a,b)


def _getSum(a, b):
while (a):
x = a & b
y = a ^ b
a = x << 1
b = y
return b

关于python - 如何在使用按位运算添加两个整数时添加无限循环的代码修复,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40208208/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com