Hamming Distance between two given integers

Objective: Given two integers, write an algorithm to calculate the hamming distance between the integers. 

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

Example:

X = 2, Y = 4
Hamming distance: 2
2 = 0 1 0
4 = 1 0 0
There are two positions at which bits are different.
X = 4, Y = 5 Hamming distance: 1 4 = 1 0 0 5 = 1 0 1 There is only one position at which bit is different.
X = 7, Y = 10 Hamming distance: 3 10 = 1 0 1 0 7 = 0 1 1 1 There are three positions at which bits are different.

Approach:

Do x XOR y. (Since in XOR, the bit is set only when both bits are different so doing x XOR y will set the bits at the places where bits are different.)

Now just count the number of set bits, this will be the hamming distance between x and y

Complete Code:

Output:

x=1, y=2, Hamming distance: 2
x=4, y=5, Hamming distance: 1
x=7, y=10, Hamming distance: 3

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: