Calculate Hamming Distance of two binary strings in C++

In this tutorial, we will learn how to calculate Hamming Distance of two binary strings in C++.

Hamming distance is the number of bits positions in which two numbers differ while comparing two binary strings of equal length.

Example:a=3 ,b=5
output: 2
Explanation:
3   [0 0 1 1]
5   [0 1 0 1]
in index 1 and 2,the value of corresponding bits are different.

Find the Hamming Distance of two binary strings in C++

In this approach, we will use XOR. So all the similar bits will become 0 and the bits which are different will remain the same. Hence for number X and Y the problem reduces to finding the number of set bits in (X^Y). We will count the number of bits by right shifting X^Y.
In C++ we have inbuilt bitset which gives set bits and these set bits can be counted by count function.

#include<bits/stdc++.h>
using namespace std;
int hammingDistance(int X,int Y)
{
   int result=X^Y;   //store the XOR output in result variable
   int count=0;
 //check each bits  stored in result
   while(result>0)    
    {
       count+=result & 1;  //storing the count of different bit
       result>>=1;        //right shift by 1
    }
   return count;   
}
int main(){
    int a,b;
    cin>>a>>b;
    cout<<hammingDistance(a,b);
    return 0;
}
input : a=3 b=5
output : 2

Also read: hamming code in C++

How to find Hamming distance between two strings in c++

Leave a Reply

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