The Hamming distance between two integers is the number of positions at which the corresponding bits are different. Given two integers x and y, return the Hamming distance between them.
Output: 2
Explanation: 1 (0001) XOR 4 (0100) = 0101. Two bits differ.
Output: 1
Explanation: 3 (011) XOR 1 (001) = 010. One bit differs.
XOR of x and y produces a number where each 1-bit represents a position where x and y differ. Count the number of 1-bits in the XOR result using the n & (n-1) trick or Java's built-in Integer.bitCount.
- Compute xor = x ^ y. Each set bit in xor indicates a differing position.
- Count the 1-bits in xor using Integer.bitCount or a manual loop.
- Return the count.
Complexity Analysis:
Time complexity: O(1) — bounded by the number of set bits (at most 32).
Space complexity: O(1) — constant extra space.