class Solution:
def hammingDistance(self, x: int, y: int) -> int:
# XOR will give a bit with 1 wherever x and y differ
xor = x ^ y
# Count the number of 1s in the binary representation
return bin(xor).count('1')
class Solution {
public:
int hammingDistance(int x, int y) {
int xorVal = x ^ y;
int count = 0;
while (xorVal) {
count += xorVal & 1;
xorVal >>= 1;
}
return count;
}
};
class Solution {
public int hammingDistance(int x, int y) {
int xor = x ^ y;
int count = 0;
while (xor != 0) {
count += xor & 1;
xor = xor >> 1;
}
return count;
}
}
var hammingDistance = function(x, y) {
let xor = x ^ y;
let count = 0;
while (xor !== 0) {
count += xor & 1;
xor = xor >> 1;
}
return count;
};
The Hamming Distance problem asks: given two integers, x
and y
, calculate the number of positions at which the corresponding bits are different in their binary representations. In other words, for each bit position, check if the bit in x
is the same as the bit in y
. If not, count that position. Return the total count.
x
and y
are non-negative integers.
To solve this problem, first consider what it means for two bits to be different. If you compare the binary representations of x
and y
bit by bit, every position where they differ should be counted.
A brute-force approach could involve converting both numbers to binary strings, padding them to the same length, and comparing each character. However, this is unnecessary because bitwise operations are designed for such tasks.
The key insight is to use the XOR operation (^
). XOR returns 1 when the bits are different and 0 when they are the same. Thus, x ^ y
gives a number whose binary representation has 1s exactly where x
and y
differ.
The final step is to count the number of 1s in the result, which directly gives the Hamming distance.
x
and y
. This operation highlights all the bit positions where the two numbers differ.x ^ y
is exactly the number of differing positions.
bin(val).count('1')
to count 1s.
Consider x = 4
and y = 1
.
100
001
Comparing bit by bit (from right to left):
So, the Hamming distance is 2.
Using XOR: 4 ^ 1 = 5
, which is 101
in binary. There are two 1s in 101
, matching our count.
The Hamming Distance problem is efficiently solved using bitwise operations. By leveraging XOR to identify differing bits and counting set bits, we avoid unnecessary conversions and comparisons. This approach is both elegant and optimal, making full use of the properties of binary arithmetic and bit manipulation.
The key insight is that XOR pinpoints differences, and counting 1s gives the answer directly. This method is fast, concise, and works across all major programming languages.