4.Hamming Distance

The Hamming distance between two integers is the number of positions at which the corresponding bits are different.

class Solution
{
public:
    int hammingDistance(int x, int y)
    {

        bitset<32> b1(x);
        bitset<32> b2(y);
        int s = 0;
        for (int i = 0; i < 32; i++)
        {
            if (b1[i] != b2[i])
            {
                s = s + 1;
            }
        }

        return s;
    }
};

Solution: (Bitwise Operations)

class Solution
{
public:
    int hammingDistance(int x, int y)
    {

        int xr = x ^ y;

        int count = 0;

        while (xr)
        {
            count++;
            xr = xr & (xr - 1);
        }

        return count;
    }
};

Last updated