text: Convert given integer X to the form 2 ^ N | C ++ 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
code: #include <bits/stdc++.h> NEW_LINE using namespace std ; const int MAX = 24 ; int countOp ( int x ) { int arr [ MAX ] ; arr [ 0 ] = 1 ; for ( int i = 1 ; i < MAX ; i ++ ) arr [ i ] = arr [ i - 1 ] * 2 ; int temp = x ; bool flag = true ; int ans ; int operations = 0 ; bool 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 ; } int main ( ) { int x = 39 ; cout << countOp ( x ) ; return 0 ; }