Monday, February 1, 2021

Hamming Distance

Problem: The Hamming distance between two integers is the number of positions at which the corresponding bits are different. You can refer wiki to understand about it more.

Example:

Input: x = 1, y = 2

Output: 2

Explanation:
1   (0 1)
2   (1 0)
     ↑ ↑


Approach: We can simply get the hamming weight of the xor of given two numbers.


Implementation in C#:

    public int HammingDistance(int x, int y) 

    {

        int xor = x^y;

        int count = 0;

        while (xor != 0)

        {

            xor = xor & (xor - 1);

            ++count;

        }

        return count;

    }


Complexity: O(num of set bits in xor of two numbers)    

No comments:

Post a Comment