
[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 time and 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);
}
}