[
bit manipulation
]
Leetcode 0461. Hamming Distance
https://leetcode.com/problems/hamming-distance
We are asked to find the number of positions, where x and y have equal bits. It is the same as finding number of 1 bits in number t = x^y. There is efficient way to find number of 1 bits in any number, using t = t&(t-1) trick: this operation in fact removes the last 1 bit from t. So, we just apply this rule in loop and increment our counter Out.
Complexity is O(k), where k is Hamming distance between numbers x and y, memory is O(1). Note, that it works (twice?) faster than usual bit counts, which have always 32 iterations.
class Solution:
def hammingDistance(self, x, y):
Out, t = 0, x^y
while t:
t, Out = t & (t-1), Out + 1
return Out
If you like the solution, you can upvote it on leetcode discussion section: Problem 0461