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, calculate the Hamming distance.

Example:

Input: x = 1, y = 4

Output: 2

Explanation:
1   (0 0 0 1)
4   (0 1 0 0)
       ↑   ↑

The above arrows point to positions where the corresponding bits are different.

Approach:

C++

#include <bits/stdc++.h>
using namespace std;

int hammingDistance(int xint y)
{
    int res = 0;
    while (x || y)
    {
        if ((x % 2 == 0 && y % 2 != 0) ||
            (x % 2 != 0 && y % 2 == 0))
        {
            res++;
        }
        x = x / 2;
        y = y / 2;
    }
    return res;
}

int main()
{
    int x = 1, y = 4;

    cout << hammingDistance(x, y);

    return 0;
}


No comments:

Post a Comment