Count minimum steps to get the given desired array | Java program to count minimum number of operations to get the given arr array ; Returns count of minimum operations to convert a zero array to arr array with increment and doubling operations . This function computes count by doing reverse steps , i . e . , convert arr to zero array . ; Initialize result ( Count of minimum moves ) ; Keep looping while all elements of arr don 't become 0. ; To store count of zeroes in current arr 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 method to test the above function
class Test { static int arr [ ] = new int [ ] { 16 , 16 , 16 } ; static int countMinOperations ( int n ) { int result = 0 ; while ( true ) { int zero_count = 0 ; int i ; for ( i = 0 ; i < n ; i ++ ) { if ( arr [ i ] % 2 == 1 ) break ; else if ( arr [ i ] == 0 ) zero_count ++ ; } if ( zero_count == n ) return result ; if ( i == n ) { for ( int j = 0 ; j < n ; j ++ ) arr [ j ] = arr [ j ] / 2 ; result ++ ; } for ( int j = i ; j < n ; j ++ ) { if ( arr [ j ] % 2 == 1 ) { arr [ j ] -- ; result ++ ; } } } } public static void main ( String [ ] args ) { System . out . println ( "Minimum number of steps required to NEW_LINE" + " get ▁ the ▁ given ▁ target ▁ array ▁ is ▁ " + countMinOperations ( arr . length ) ) ; } }