I have found some code that takes two binary string inputs and sums them
:
def addBinary(a, b) -> str:
x, y = int(a, 2), int(b, 2)
while y:
answer = x ^ y
carry = (x & y) << 1
x, y = answer, carry
return bin(x)[2:]
While I do understand what is happening on a high level; in particular that we start by XORing the two input integers, which gives us the sum of the two numbers WITHOUT the 'carry'.
Then we calculate the carry at each stage and add it, and this gets us the final answer. But it is the 'carry'
part that I don't quite understand. From the second iteration of the while loop, we are taking the answer x (sum of the two input numbers)
and the current carry y(?)
and by doing carry = (x & y) << 1
we obtain the next carry
?
So basically I don't quite understand/want to confirm how we are taking into account the carry at each stage- can someone please explain? Thanks!