Hamming Distance
Easy bit-manipulation
Description
Constraints
0 <= a, b <= 10^9
Examples
Input: a = 1, b = 4
Output: 2
001 vs 100
Hints (1)
- XOR marks differing bits; count the set bits of the result.
Solutions
Popcount of the XOR. · Time O(bits) · Space O(1)
func hammingDistance(a, b int) int {
x := a ^ b
count := 0
for x > 0 {
x &= x - 1
count++
}
return count
}
Popcount of the XOR. · Time O(bits) · Space O(1)
function hammingDistance(a, b) {
let x = a ^ b, count = 0;
while (x > 0) { x &= x - 1; count++; }
return count;
}
Popcount of the XOR. · Time O(bits) · Space O(1)
function hammingDistance($a, $b) {
$x = $a ^ $b; $count = 0;
while ($x > 0) { $x &= $x - 1; $count++; }
return $count;
}
Popcount of the XOR. · Time O(bits) · Space O(1)
def hammingDistance(a, b):
return bin(a ^ b).count("1")
Popcount of the XOR. · Time O(bits) · Space O(1)
function hammingDistance(a: number, b: number): number {
let x = a ^ b, count = 0;
while (x > 0) { x &= x - 1; count++; }
return count;
}
Create a free account to submit solutions, track progress and save problems.
Create account