461. Hamming Distance
Problem
Return the Hamming distance between x and y: the number of bit positions in which they differ.
Example: x = 1, y = 4 → 2 (001 vs 100)
Differing bits = set bits of x ^ y.
Complexity: O(1).
class Solution:
def hammingDistance(self, x: int, y: int) -> int:
return bin(x ^ y).count("1")
assert Solution().hammingDistance(1, 4) == 2
assert Solution().hammingDistance(3, 1) == 1
class Solution {
public int hammingDistance(int x, int y) { return Integer.bitCount(x ^ y); }
}
func hammingDistance(x int, y int) int {
return bits.OnesCount(uint(x ^ y)) // the differing bits
}