这是原件question https://stackoverflow.com/questions/39113479/infinite-loop-while-adding-two-integers-using-bitwise-operations-in-python-3.
以下是使用按位运算将两个整数相加的代码:
def getSum(self, a, b):
while (a & b):
x = a & b
y = a ^ b
a = x << 1
b = y
return a ^ b
虽然我知道它在添加正整数和负整数时进入无限循环的原因,但我需要一些帮助来为此提供代码修复。
我假设您已经了解了无限循环背后的逻辑。logic https://stackoverflow.com/questions/39113479/infinite-loop-while-adding-two-integers-using-bitwise-operations-in-python-3
以下是您的程序的行为:
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
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)