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
function MinimumCost ( a , n , x ) { for ( i = 1 ; i < n ; i ++ ) { a [ i ] = Math . min ( a [ i ] , 2 * a [ i - 1 ] ) ; } var ind = 0 ; var sum = 0 ; while ( x > 0 ) { if ( x != 0 ) sum += a [ ind ] ; ind ++ ; x = x >> 1 ; } return sum ; } var a = [ 20 , 50 , 60 , 90 ] ; var x = 7 ; var n = a . length ; document . write ( MinimumCost ( a , n , x ) ) ;