Minimum cost to form a number X by adding up powers of 2 | Function to return the minimum cost ; Re - compute the array ; Add answers for set bits ; If bit is set ; Increase the counter ; Right shift the number ; Driver code
def MinimumCost ( a , n , x ) : NEW_LINE INDENT for i in range ( 1 , n , 1 ) : NEW_LINE INDENT a [ i ] = min ( a [ i ] , 2 * a [ i - 1 ] ) NEW_LINE DEDENT ind = 0 NEW_LINE sum = 0 NEW_LINE while ( x ) : NEW_LINE INDENT if ( x & 1 ) : NEW_LINE INDENT sum += a [ ind ] NEW_LINE DEDENT ind += 1 NEW_LINE x = x >> 1 NEW_LINE DEDENT return sum NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT a = [ 20 , 50 , 60 , 90 ] NEW_LINE x = 7 NEW_LINE n = len ( a ) NEW_LINE print ( MinimumCost ( a , n , x ) ) NEW_LINE DEDENT