Count number of bits to be flipped to convert A to B | Set | Java 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
import java . util . * ; class GFG { static int countBits ( int a , int b ) { int count = 0 ; while ( a > 0 b > 0 ) { 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 ; } public static void main ( String [ ] args ) { int a = 10 , b = 7 ; System . out . println ( countBits ( a , b ) ) ; } }