Count minimum steps to get the given desired array | C ++ program to count minimum number of operations to get the given target array ; Returns count of minimum operations to convert a zero array to target array with increment and doubling operations . This function computes count by doing reverse steps , i . e . , convert target to zero array . ; Initialize result ( Count of minimum moves ) ; Keep looping while all elements of target don 't become 0. ; To store count of zeroes in current target array ; To find first odd element ; If odd number found ; If 0 , then increment zero_count ; All numbers are 0 ; All numbers are even ; Divide the whole array by 2 and increment result ; Make all odd numbers even by subtracting one and increment result . ; Driver program to test above functions
#include <bits/stdc++.h> NEW_LINE using namespace std ; int countMinOperations ( unsigned int target [ ] , int n ) { int result = 0 ; while ( 1 ) { int zero_count = 0 ; int i ; for ( i = 0 ; i < n ; i ++ ) { if ( target [ i ] & 1 ) break ; else if ( target [ i ] == 0 ) zero_count ++ ; } if ( zero_count == n ) return result ; if ( i == n ) { for ( int j = 0 ; j < n ; j ++ ) target [ j ] = target [ j ] / 2 ; result ++ ; } for ( int j = i ; j < n ; j ++ ) { if ( target [ j ] & 1 ) { target [ j ] -- ; result ++ ; } } } } int main ( ) { unsigned int arr [ ] = { 16 , 16 , 16 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << " Minimum ▁ number ▁ of ▁ steps ▁ required ▁ to ▁ " " get ▁ the ▁ given ▁ target ▁ array ▁ is ▁ " << countMinOperations ( arr , n ) ; return 0 ; }