text: Convert given integer X to the form 2 ^ N | Python3 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: MAX = 24 ; NEW_LINE def countOp ( x ) : NEW_LINE INDENT arr = [ 0 ] * MAX ; NEW_LINE arr [ 0 ] = 1 ; NEW_LINE for i in range ( 1 , MAX ) : NEW_LINE INDENT arr [ i ] = arr [ i - 1 ] * 2 ; NEW_LINE DEDENT temp = x ; NEW_LINE flag = True ; NEW_LINE ans = 0 ; NEW_LINE operations = 0 ; NEW_LINE flag2 = False ; NEW_LINE for i in range ( MAX ) : NEW_LINE INDENT if ( arr [ i ] - 1 == x ) : NEW_LINE INDENT flag2 = True ; NEW_LINE DEDENT if ( arr [ i ] > x ) : NEW_LINE INDENT ans = i ; NEW_LINE break ; NEW_LINE DEDENT DEDENT if ( flag2 ) : NEW_LINE INDENT return 0 ; NEW_LINE DEDENT while ( flag ) : NEW_LINE INDENT if ( arr [ ans ] < x ) : NEW_LINE INDENT ans += 1 ; NEW_LINE DEDENT operations += 1 ; NEW_LINE for i in range ( MAX ) : NEW_LINE INDENT take = x ^ ( arr [ i ] - 1 ) ; NEW_LINE if ( take <= arr [ ans ] - 1 ) : NEW_LINE INDENT if ( take > temp ) : NEW_LINE INDENT temp = take ; NEW_LINE DEDENT DEDENT DEDENT if ( temp == arr [ ans ] - 1 ) : NEW_LINE INDENT flag = False ; NEW_LINE break ; NEW_LINE DEDENT temp += 1 ; NEW_LINE operations += 1 ; NEW_LINE x = temp ; NEW_LINE if ( x == arr [ ans ] - 1 ) : NEW_LINE INDENT flag = False ; NEW_LINE DEDENT DEDENT return operations ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT x = 39 ; NEW_LINE print ( countOp ( x ) ) ; NEW_LINE DEDENT