Hamming Distance
Easy · Bit Manipulation · Explanation and code example
Compare Bits and Shift
How it works
At each position, XOR the two low bits to determine whether they differ. Add that contribution and shift both values right. Continue until neither value has remaining set bits.
Steps
- Initialize the distance to zero.
- Add (x & 1) XOR (y & 1).
- Shift both values until both are zero.
Complexity
- Time: O(log(max(x, y) + 1)), at most the fixed input bit width.
- Space: O(1).
Things to watch for
- Use XOR to detect different bits.
- Equal inputs have distance zero.
- The problem supplies nonnegative integers.
Python code example
class Solution:
def hammingDistance(self, x: int, y: int) -> int:
ans = 0
while x > 0 or y > 0:
ans += (x & 1) ^ (y & 1)
x >>= 1
y >>= 1
return ans
C++ code example
class Solution {
public:
int hammingDistance(int x, int y) {
int ans = 0;
while (x > 0 || y > 0) {
ans += (x & 1) ^ (y & 1);
x >>= 1;
y >>= 1;
}
return ans;
}
};
Source and license
Explanation by LC Tracker. Code adapted from walkccc / Peng-Yu Chen · MIT license. Node types are supplied by LeetCode where needed.