Complete-Preparation

๐ŸŽ‰ One-stop destination for all your technical interview Preparation ๐ŸŽ‰

View the Project on GitHub

461. Hamming Distance ๐ŸŒŸ

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.

Original Post - 4 Solutions

Converting Binary Form to String/Array & Iterating

class Solution {
public:
    int hammingDistance(int x, int y) {
        bitset<32> xb(x), yb(y);
        int ans = 0;
        for(int i = 0; i < 32; i++)
            ans += (xb[i] != yb[i]);
        return ans;
    }
};

Iterating & Comparing each Bit

class Solution {
public:
    int hammingDistance(int x, int y) {
        int ans = 0;
        for(int i = 0; i < 32; i++)
            ans += ((x >> i & 1) != (y >> i & 1));
        return ans;
    }
};

XOR & count bits

class Solution {
public:
    int hammingDistance(int x, int y) {
        int Xor = x ^ y, ans = 0;
        for(int i = 0; i < 32; i++)
            ans += ((Xor & (1 << i)) != 0);
        return ans;
    }
};

Brian-Kernighanโ€™s method

class Solution {
public:
    int hammingDistance(int x, int y) {
        int XOR = x ^ y, ans = 0;
        while(XOR) {
            XOR &= XOR-1; // n&(n-1) clears the rightmost set bit
            ans++;
        }
        return ans;
    }
};

๐Ÿ’ก Note:

  1. The number of bits N for this problem is fixed to 32. So, strictly speaking, the time complexity of 1st three solutions is O(N) = O(32) = O(1). But to differentiate between time complexities of 1st three and last approach, I have denoted them as O(N).
  2. Itโ€™s likely that if you got such a question during an interview, you will probably be expected to come up with an approach similar to this one. This approach performs the least number of loops to find the number of set bits in a number which is equal to the number of set bits in the number itself.