I am trying to solve a problem, using python code, which requires me to add two integers without the use of '+' or '-' operators. I have the following code which works perfectly for two positive numbers:
def getSum(self, a, b):
while (a & b):
x = a & b
y = a ^ b
a = x << 1
b = y
return a ^ b
This piece of code works perfectly if the input is two positive integers or two negative integers but it fails when one number is positive and other is negative. It goes into an infinite loop. Any idea as to why this might be happening?
EDIT: Here is the link discussing the code fix for this.
aandb? Print or watch the values ofaandbduring the loop - do they fall into a repeating pattern? Also, does it make a difference whetheraorbis the negative operand?