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

1.8

Given two numbers ‘a’ and b’. Write a program to count number of bits needed 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
We need to flip highlighted four bits in a
to make it b.

Input : a = 7, b = 10
Output : 3
Binary representation of a is 00000111
Binary representation of b is 00001010
We need to flip highlighted three bits in a
to make it b.
  1. Calculate XOR of A and B.      
        a_xor_b = A ^ B
  2. Count the set bits in the above 
     calculated XOR result.
        countSetBits(a_xor_b)

XOR of two number will have set bits only at those places where A differs from B.

// Count number of bits to be flipped
// to covert A into B
#include <iostream>
using namespace std;

// Function that count set bits
int countSetBits(int n)
{
    int count = 0;
    while (n)
    {
        count += n & 1;
        n >>= 1;
    }
    return count;
}

// Function that return count of
// flipped number
int FlippedCount(int a, int b)
{
    // Return count of set bits in
    // a XOR b
    return countSetBits(a^b);
}

// Driver code
int main()
{
    int a = 10;
    int b = 20;
    cout << FlippedCount(a, b)<<endl;
    return 0;
}

Output :

4

Thanks to Sahil Rajput for providing above implementation.

To get the set bit count please see this post: Count set bits in an integer

Asked in: Amazon, Samsung

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.

GATE CS Corner    Company Wise Coding Practice

Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.

Recommended Posts:



1.8 Average Difficulty : 1.8/5.0
Based on 91 vote(s)










Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.