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

07 Sep, 2021
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.  
C++
Java
Python3
C#
PHP
Javascript
// Count number of bits to be flipped// to convert A into B#include <iostream>using namespace std; // Function that count set bitsint countSetBits(int n){    int count = 0;    while (n > 0)    {        count++;        n &= (n-1);    }    return count;} // Function that return count of// flipped numberint FlippedCount(int a, int b){    // Return count of set bits in    // a XOR b    return countSetBits(a^b);} // Driver codeint main(){    int a = 10;    int b = 20;    cout << FlippedCount(a, b)<<endl;    return 0;}
// Count number of bits to be flipped// to convert A into Bimport 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;        System.out.print(FlippedCount(a, b));    }} // This code is contributed by rishabh_jain
# Count number of bits to be flipped# to convert A into B # Function that count set bitsdef countSetBits( n ):    count = 0    while n:        count += 1        n &= (n-1)    return count     # Function that return count of# flipped numberdef FlippedCount(a , b):     # Return count of set bits in    # a XOR b    return countSetBits(a^b) # Driver codea = 10b = 20print(FlippedCount(a, b)) # This code is contributed by "Sharad_Bhardwaj".
// Count number of bits to be// flipped to convert A into Busing 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;        Console.WriteLine(FlippedCount(a, b));    }} // This code is contributed by vt_m.
<?php// Count number of bits to be// flipped to convert A into B // Function that count set bitsfunction countSetBits($n){    $count = 0;    while($n)    {        $count += 1;        $n &= (n-1);    }    return $count;}     // Function that return// count of flipped numberfunction FlippedCount($a, $b){    // Return count of set    // bits in a XOR b    return countSetBits($a ^ $b);} // Driver code$a = 10;$b = 20;echo FlippedCount($a, $b); // This code is contributed by mits?>
<script>// 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</script>
4
C++
Java
Python3
C#
Javascript
// C++ program#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
/*package whatever //do not write package name here */ // 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;    }           public static void main (String[] args) {        int a = 10;          int b = 20;          System.out.println(countFlips(a, b));    }   }
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     a = 10b = 20print(countFlips(a, b)) # This code is contributed by shivanisinghss2110
/*package whatever //do not write package name here */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;          Console.Write(countFlips(a, b));    }   } // This code is contributed by shivanisinghss2110
<script>/*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</script>
4
Thanks to Sahil Rajput for providing above implementation. 
YouTubeGeeksforGeeks507K subscribersCount number of bits to be flipped to convert A to B | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 2:49•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=WVgYaucD1S4" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>
To get the set bit count please see this post: Count set bits in an integerIf 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. 
Mithun Kumar
shaik asra
shikhasingrajput
praveenvishwakarma11063
shivanisinghss2110
Amazon
Bitwise-XOR
Qualcomm
Samsung
Bit Magic
Amazon
Samsung
Qualcomm
Bit Magic
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Cyclic Redundancy Check and Modulo-2 Division
Add two numbers without using arithmetic operators
Bits manipulation (Important tactics)
Bit Fields in C
Find the element that appears once
Set, Clear and Toggle a given bit of a number in C
C++ bitset and its application
Divide two integers without using multiplication, division and mod operator
1's and 2's complement of a Binary Number
Check whether K-th bit is set or not