Skip to content
Related Articles

Related Articles

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

Improve Article
Save Article
  • Difficulty Level : Easy
  • Last Updated : 09 Sep, 2022
Improve Article
Save Article

Given two numbers A and B. Write a program to count the number of bits needed to be flipped to convert A to B

Examples: 

Input: A = 10, B = 20
Output: 4
Explanation: 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
Explanation: 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.
 

Recommended Practice

Count the number of bits to be flipped to convert A to B using the XOR operator:

To solve the problem follow the below idea:

Calculate (A XOR B), since 0 XOR 1 and 1 XOR 0 is equal to 1. So calculating the number of set bits in A XOR B will give us the count of the number of unmatching bits in A and B, which needs to be flipped

Follow the given steps to solve the problem:

  • Calculate the XOR of A and B
  • Count the set bits in the above-calculated XOR result
  • Return the count

Below is the implementation of the above approach:

C




// C program for the above approach
#include <stdio.h>
 
// Function that count set bits
int countSetBits(int n)
{
    int count = 0;
    while (n > 0) {
        count++;
        n &= (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;
   
      // Function call
    printf("%d\n", FlippedCount(a, b));
    return 0;
}
 
// This code is contributed by Sania Kumari Gupta
// (kriSania804)

C++




// C++ program for the above approach
#include <bits/stdc++.h>
using namespace std;
 
// Function that count set bits
int countSetBits(int n)
{
    int count = 0;
    while (n > 0) {
        count++;
        n &= (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;
   
      // Function call
    cout << FlippedCount(a, b) << endl;
    return 0;
}
 
// This code is contributed by Sania Kumari Gupta
// (kriSania804)

Java




// Java program for the above approach
import java.util.*;
 
class Count {
 
    // Function that count set bits
    public static int countSetBits(int n)
    {
        int count = 0;
        while (n != 0) {
            count++;
            n &= (n - 1);
        }
        return count;
    }
 
    // Function that return count of
    // flipped number
    public static int FlippedCount(int a, int b)
    {
        // Return count of set bits in
        // a XOR b
        return countSetBits(a ^ b);
    }
 
    // Driver code
    public static void main(String[] args)
    {
        int a = 10;
        int b = 20;
       
          // Function call
        System.out.print(FlippedCount(a, b));
    }
}
 
// This code is contributed by rishabh_jain

Python3




# Python3 program for the above approach
 
# Function that count set bits
 
 
def countSetBits(n):
    count = 0
    while n:
        count += 1
        n &= (n-1)
    return count
 
# Function that return count of
# flipped number
 
 
def FlippedCount(a, b):
 
    # Return count of set bits in
    # a XOR b
    return countSetBits(a ^ b)
 
 
# Driver code
if __name__ == "__main__":
  a = 10
  b = 20
 
  # Function call
  print(FlippedCount(a, b))
 
# This code is contributed by "Sharad_Bhardwaj".

C#




// C# program for the above approach
 
using System;
 
class Count {
 
    // Function that count set bits
    public static int countSetBits(int n)
    {
        int count = 0;
        while (n != 0) {
            count++;
            n &= (n - 1);
        }
        return count;
    }
 
    // Function that return
    // count of flipped number
    public static int FlippedCount(int a, int b)
    {
        // Return count of set
        // bits in a XOR b
        return countSetBits(a ^ b);
    }
 
    // Driver code
    public static void Main()
    {
        int a = 10;
        int b = 20;
       
          // Function call
        Console.WriteLine(FlippedCount(a, b));
    }
}
 
// This code is contributed by vt_m.

PHP




<?php
// php program for the above approach
 
// Function that count set bits
function countSetBits($n)
{
    $count = 0;
    while($n)
    {
        $count += 1;
        $n &= (n-1);
    }
    return $count;
}
     
// Function that return
// count of flipped number
function FlippedCount($a, $b)
{
    // Return count of set
    // bits in a XOR b
    return countSetBits($a ^ $b);
}
 
// Driver code
$a = 10;
$b = 20;
 
// Function call
echo FlippedCount($a, $b);
 
// This code is contributed by mits
?>

Javascript




// Count number of bits to be flipped
// to convert A into Bclass Count {
 
    // Function that count set bits
    function countSetBits(n) {
        var count = 0;
        while (n != 0) {
            count++;
            n &= (n - 1);
        }
        return count;
    }
 
    // Function that return count of
    // flipped number
    function FlippedCount(a , b) {
        // Return count of set bits in
        // a XOR b
        return countSetBits(a ^ b);
    }
 
    // Driver code
        var a = 10;
        var b = 20;
        document.write(FlippedCount(a, b));
 
// This code is contributed by shikhasingrajput

Output

4

Note: Set bits in (a XOR b) can also be computer using built in function __builtin_popcount() in C/C++

Below is the implementation of the above approach:

C




//C program to Count number of bits to be flipped
// to convert A into B
#include <stdio.h>
 
// Driver code
int main()
{
    int a = 10;
    int b = 20;
   
      // Function call
    printf("%d\n",__builtin_popcount(a^b));
    return 0;
}
 
// This code is contributed by Suruchi Kumari

C++




// C++ program to Count number of bits to be flipped
// to convert A into B
#include <iostream>
using namespace std;
 
// Driver code
int main()
{
    int a = 10;
    int b = 20;
   
      // Function call
    cout <<__builtin_popcount(a^b) << endl;
    return 0;
}
 
// This code is contributed by Suruchi Kumari

Output

4

Time Complexity: O(K) where K is the number of bits
Auxiliary Space: O(1) 

Count the number of bits to be flipped to convert A to B using the AND operator:

To solve the problem follow the below idea:

Start comparing the bits in A and B, starting from the least significant bit and if (A & 1) is not equal to (B & 1) then the current bit needs to be flipped, as the value of bits is different at this position in both the numbers

Follow the given steps to solve the problem:

  • Declare variable flips equal to zero
  • Run a loop, while a is greater than zero and b is also greater than zero
    • Calculate values of (A AND 1) and (B AND 1)
    • If these values are not equal then increase the flip value by 1
    • Right shift a and b by 1
  • Return flips

Below is the implementation of the above approach:

C++




// C++ program for the above approach
#include <iostream>
using namespace std;
 
int countFlips(int a, int b)
{
 
    // initially flips is equal to 0
    int flips = 0;
 
    // & each bits of a && b with 1
    // and store them if t1 and t2
    // if t1 != t2 then we will flip that bit
 
    while (a > 0 || b > 0) {
 
        int t1 = (a & 1);
        int t2 = (b & 1);
 
        if (t1 != t2) {
            flips++;
        }
        // right shifting a and b
        a >>= 1;
        b >>= 1;
    }
 
    return flips;
}
 
int main()
{
    int a = 10;
    int b = 20;
    cout << countFlips(a, b);
}
 
// this code is contributed by shivanisinghss2110

Java




// Java program for the above approach
 
// CONTRIBUTED BY PRAVEEN VISHWAKARMA
 
import java.io.*;
 
class GFG {
 
    public static int countFlips(int a, int b)
    {
        // initially flips is equal to 0
        int flips = 0;
 
        // & each bits of a && b with 1
        // and store them if t1 and t2
        // if t1 != t2 then we will flip that bit
 
        while (a > 0 || b > 0) {
 
            int t1 = (a & 1);
            int t2 = (b & 1);
 
            if (t1 != t2) {
                flips++;
            }
            // right shifting a and b
            a >>>= 1;
            b >>>= 1;
        }
 
        return flips;
    }
 
    // Driver code
    public static void main(String[] args)
    {
        int a = 10;
        int b = 20;
         
          // Function call
        System.out.println(countFlips(a, b));
    }
}

Python3




# Python3 program for the above approach
 
 
def countFlips(a, b):
 
    # initially flips is equal to 0
    flips = 0
 
    # & each bits of a && b with 1
    # and store them if t1 and t2
    # if t1 != t2 then we will flip that bit
    while(a > 0 or b > 0):
        t1 = (a & 1)
        t2 = (b & 1)
        if(t1 != t2):
            flips += 1
 
        # right shifting a and b
        a >>= 1
        b >>= 1
 
    return flips
 
 
# Driver code
if __name__ == "__main__":
  a = 10
  b = 20
 
  # Function call
  print(countFlips(a, b))
 
# This code is contributed by shivanisinghss2110

C#




// C# program for the above approach
using System;
 
class GFG {
 
    public static int countFlips(int a, int b)
    {
 
        // initially flips is equal to 0
        int flips = 0;
 
        // & each bits of a && b with 1
        // and store them if t1 and t2
        // if t1 != t2 then we will flip that bit
        while (a > 0 || b > 0) {
 
            int t1 = (a & 1);
            int t2 = (b & 1);
 
            if (t1 != t2) {
                flips++;
            }
            // right shifting a and b
            a >>= 1;
            b >>= 1;
        }
 
        return flips;
    }
 
    // Driver code
    public static void Main(String[] args)
    {
        int a = 10;
        int b = 20;
       
          // Function call
        Console.Write(countFlips(a, b));
    }
}
 
// This code is contributed by shivanisinghss2110

Javascript




/*package whatever //do not write package name here */
 
function countFlips(a, b){
          // initially flips is equal to 0
        var flips = 0;
       
          // & each bits of a && b with 1
          // and store them if t1 and t2
        // if t1 != t2 then we will flip that bit
         
          while(a>0 || b>0){
           
            var t1 = (a&1);
              var t2 = (b&1);
               
              if(t1!=t2){
                flips++;
            }
              // right shifting a and b
              a>>>=1;
              b>>>=1;
        }
       
      return flips;
    }
       
          var a = 10;
          var b = 20;
          document.write(countFlips(a, b));
 
// This code is contributed by shivanisinghss2110

Output

4

Time Complexity: O(K) where K is the number of bits
Auxiliary Space: O(1)

Thanks to Sahil Rajput for providing the above implementation.
If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@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.


My Personal Notes arrow_drop_up
Related Articles

Start Your Coding Journey Now!