Convert given integer X to the form 2 ^ N | Java implementation of the approach ; Function to return the count of operations required ; To store the powers of 2 ; Temporary variable to store x ; To store the index of smaller number larger than x ; To store the count of operations ; Stores the index of number in the form of 2 ^ n - 1 ; If x is already in the form 2 ^ n - 1 then no operation is required ; If number is less than x increase the index ; Calculate all the values ( x xor 2 ^ n - 1 ) for all possible n ; Only take value which is closer to the number ; If number is in the form of 2 ^ n - 1 then break ; Return the count of operations required to obtain the number ; Driver code
import java . io . * ; class GFG { static int MAX = 24 ; static int countOp ( int x ) { int arr [ ] = new int [ MAX ] ; arr [ 0 ] = 1 ; for ( int i = 1 ; i < MAX ; i ++ ) arr [ i ] = arr [ i - 1 ] * 2 ; int temp = x ; boolean flag = true ; int ans = 0 ; int operations = 0 ; boolean flag2 = false ; for ( int i = 0 ; i < MAX ; i ++ ) { if ( arr [ i ] - 1 == x ) flag2 = true ; if ( arr [ i ] > x ) { ans = i ; break ; } } if ( flag2 ) return 0 ; while ( flag ) { if ( arr [ ans ] < x ) ans ++ ; operations ++ ; for ( int i = 0 ; i < MAX ; i ++ ) { int take = x ^ ( arr [ i ] - 1 ) ; if ( take <= arr [ ans ] - 1 ) { if ( take > temp ) temp = take ; } } if ( temp == arr [ ans ] - 1 ) { flag = false ; break ; } temp ++ ; operations ++ ; x = temp ; if ( x == arr [ ans ] - 1 ) flag = false ; } return operations ; } public static void main ( String [ ] args ) { int x = 39 ; System . out . println ( countOp ( x ) ) ; } }