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
< ? php function MinimumCost ( $ a , $ n , $ x ) { for ( $ i = 1 ; $ i < $ n ; $ i ++ ) { $ a [ $ i ] = min ( $ a [ $ i ] , 2 * $ a [ $ i - 1 ] ) ; } $ ind = 0 ; $ sum = 0 ; while ( $ x ) { if ( $ x & 1 ) $ sum += $ a [ $ ind ] ; $ ind ++ ; $ x = $ x >> 1 ; } return $ sum ; } $ a = array ( 20 , 50 , 60 , 90 ) ; $ x = 7 ; $ n = sizeof ( $ a ) / sizeof ( $ a [ 0 ] ) ; echo MinimumCost ( $ a , $ n , $ x ) ; ? >