Solving some leetcode question I encountered the hamming distance problem (which I almost forget).
the question was: Given two integers, return the Hamming distance between them.
Now, I know and understand the following logic:
def hammingDistance(self, x: int, y: int) -> int:
x = x ^ y
distance = 0
while x:
if x & 1:
distance += 1
x = x // 2
return distance
but if replacing the while loop, with:
while x:
x = x & (x-1)
distance += 1
I don't understand the logic that the AND operation achieving. It do an AND operation on the XOR operation, and its previous number. But I dont understand what is the Invariant here.
can someone explain it? Thanks!