The following function determines the number of bits you would need to flip to convert integer A to integer B. I have solved it by a different method, but when I read this solution I don't understand it. It clearly works, but my question is why?
def bit_swap_required(a: int, b: int) -> int:
count, c = 0, a ^ b
while c:
count, c = count + 1, c & (c - 1)
return count
I understand why we do a^b. It gives us a '1' at every place we need to flip. But, How does doing c & (c-1) repeatedly give you the EXACT number of '1's in the number?