Archive

LeetCode. 461. Hamming Distance

Archived technical note: LeetCode. 461. Hamming Distance.

image

[Link] https://leetcode.com/problems/hamming-distance/

XOR sets a bit to 1 exactly where the corresponding bits of x and y differ, so x ^ y marks every differing position. Integer.bitCount counts those set bits, which is the Hamming distance.

Java integers have a fixed width of 32 bits, so the operation takes O(1)O(1) time and O(1)O(1) extra space.


class Solution {
    public int hammingDistance(int x, int y) {
        // XOR sets a bit exactly where the two inputs differ.
        // bitCount counts those differing positions.
        return Integer.bitCount(x ^ y);
    }
}