这是原始question
以下是使用按位运算添加两个整数的代码:
def getSum(self, a, b):
while (a & b):
x = a & b
y = a ^ b
a = x << 1
b = y
return a ^ b
虽然我知道它在添加正整数和负整数时进入无限循环的原因,但我需要一些帮助来为此提出代码修复。
答案 0 :(得分:2)
我假设你已经完成了你所获得的无限循环背后的逻辑。 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