Problem: Given two numbers A and B. Write a program to count number of bits needed to be flipped to convert A to B.
For example:
For example:
Input: A = 12 and B = 22 Output: 3 Binary representation of 12 is 001100 Binary representation of 22 is 010110 Here we need to flip 3 bits in A to convert it to B. Input: A = 10 and B = 20 Output: 4 Binary representation of 10 is 001010 Binary representation of 20 is 010100 Here we need to flip 4 bits in A to convert it to B.Approach: Here we will use XOR operator to calculate our result.
- Calculate XOR of A and B.
- x = A ^ B
- Count the set bits in x calculated above.
#include <bits/stdc++.h>
using namespace std;
/* function to calculate number of flips */
int numFlip(int A, int B)
{
/* A xor B */
int x = A ^ B;
int count = 0;
while(x)
{
count += x & 1;
x >>= 1;
}
return count;
}
/* driver function */
int main()
{
int A, B;
A = 12; B = 22;
cout<<numFlip(A, B)<<"\n";
A = 10; B = 20;
cout<<numFlip(A, B)<<"\n";
return 0;
}
Output:
3 4