Minimum cost to form a number X by adding up powers of 2 | Java implementation of the approach ; 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
import java . io . * ; class GFG { static int MinimumCost ( int a [ ] , int n , int x ) { for ( int i = 1 ; i < n ; i ++ ) { a [ i ] = Math . min ( a [ i ] , 2 * a [ i - 1 ] ) ; } int ind = 0 ; int sum = 0 ; while ( x > 0 ) { if ( x != 0 ) sum += a [ ind ] ; ind ++ ; x = x >> 1 ; } return sum ; } public static void main ( String [ ] args ) { int a [ ] = { 20 , 50 , 60 , 90 } ; int x = 7 ; int n = a . length ; System . out . println ( MinimumCost ( a , n , x ) ) ; } }