Minimum cost to form a number X by adding up powers of 2 | C ++ 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
#include <bits/stdc++.h> NEW_LINE using namespace std ; int MinimumCost ( int a [ ] , int n , int x ) { for ( int i = 1 ; i < n ; i ++ ) { a [ i ] = min ( a [ i ] , 2 * a [ i - 1 ] ) ; } int ind = 0 ; int sum = 0 ; while ( x ) { if ( x & 1 ) sum += a [ ind ] ; ind ++ ; x = x >> 1 ; } return sum ; } int main ( ) { int a [ ] = { 20 , 50 , 60 , 90 } ; int x = 7 ; int n = sizeof ( a ) / sizeof ( a [ 0 ] ) ; cout << MinimumCost ( a , n , x ) ; return 0 ; }