python-3.xbit-manipulationbitwise-operatorshamming-distance

Hamming Distance: unclear logic step involving bitwise operation


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!


Solution

  • In your second code snippet, x & (x-1) clears the least significant bit that is '1' (not '0') in the binary representation of x, i.e. it turns off the rightmost set bit. Each time you perform this operation, you're basically counting and removing the rightmost '1' bit from the binary representation of x. Since each bit that is '1' in the XOR result represents a differing bit between x and y, counting these cleared bits gives you the Hamming distance.