Count number of bits to be flipped to convert A to B | Set | C ++ implementation of the approach ; Function to return the count of bits to be flipped to convert a to b ; To store the required count ; Loop until both of them become zero ; Store the last bits in a as well as b ; If the current bit is not same in both the integers ; Right shift both the integers by 1 ; Return the count ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int countBits ( int a , int b ) { int count = 0 ; while ( a b ) { int last_bit_a = a & 1 ; int last_bit_b = b & 1 ; if ( last_bit_a != last_bit_b ) count ++ ; a = a >> 1 ; b = b >> 1 ; } return count ; } int main ( ) { int a = 10 , b = 7 ; cout << countBits ( a , b ) ; return 0 ; }