Hamming Distance

easy bit manipulation

Problem

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.

Inputx = 1, y = 4
Output2
1 = 0001, 4 = 0100. Bits at positions 0 and 2 differ.

def hamming_distance(x, y):
    z = x ^ y
    count = 0
    while z:
        z &= z - 1
        count += 1
    return count
function hammingDistance(x, y) {
  let z = x ^ y;
  let count = 0;
  while (z) {
    z &= z - 1;
    count++;
  }
  return count;
}
class Solution {
    public int hammingDistance(int x, int y) {
        return Integer.bitCount(x ^ y);
    }
}
int hammingDistance(int x, int y) {
    return __builtin_popcount(x ^ y);
}
Time: O(k) where k is the number of set bits in x⊕y Space: O(1)