Count number of bits to be flipped to convert A to B

Problem Statement:

You are given 2 integers A and B.
You need to findout the number of bits to be flipped to convert A to B.

Example

Input : a = 10, b = 20
Output : 4
Binary representation of a is 00001010
Binary representation of b is 00010100
a XOR b =00011110
The number of set bits are 4.

Solution

Solution is very simple.
We need to XOR the elements.
Then count the number of set bits to arrive at the solution.

Solution in C++

#include <vector>    
#include <algorithm>  
//visit www.ProDeveloperTutorial.com for 450+ solved questions  
#include <iostream>    
#include <string>
#include <unordered_set>
#include <queue>

using namespace std;

int count_set_bits(int n) 
{ 
    int count = 0; 

    while (n > 0) 
    { 
        count++; 
        n &= (n-1); 
    } 
    return count; 
} 
  
int count_bits_to_be_flipped(int a, int b) 
{ 
    int temp = a^b;
    return count_set_bits(temp); 
} 
  
int main() 
{ 
    int a = 10; 
    int b = 20; 
    cout << "The number of set bits are : "<< count_bits_to_be_flipped(a, b)<<endl; 
    return 0; 
} 

Output:

The number of set bits are : 4
Write a Comment

Leave a Comment

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