Minimum number of operations required to obtain a given Binary String | Function to find the minimum number of operations required to obtain the string s ; Iterate the string s ; If first occurrence of 1 is found ; Mark the index ; Base case : If no 1 occurred ; No operations required ; Stores the character for which last operation was performed ; Stores minimum number of operations ; Iterate from pos to n ; Check if s [ i ] is 0 ; Check if last operation was performed because of 1 ; Set last to 0 ; Check if last operation was performed because of 0 ; Set last to 1 ; Return the answer ; Driver Code
function minOperations ( s ) { let n = s . length ; let pos = - 1 ; for ( let i = 0 ; i < s . length ; i ++ ) { if ( s [ i ] == ' ' ) { pos = i ; break ; } } if ( pos == - 1 ) { return 0 ; } let last = 1 ; let ans = 1 ; for ( let i = pos + 1 ; i < n ; i ++ ) { if ( s [ i ] == ' ' ) { if ( last == 1 ) { ans ++ ; last = 0 ; } } else { if ( last == 0 ) { ans ++ ; last = 1 ; } } } return ans ; } let s = " " ; document . write ( minOperations ( s ) ) ;