Minimum number of operations required to obtain a given Binary String | Java program to implement the above approach ; 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
import java . util . * ; class GFG { static int minOperations ( String s ) { int n = s . length ( ) ; int pos = - 1 ; for ( int i = 0 ; i < s . length ( ) ; i ++ ) { if ( s . charAt ( i ) == '1' ) { pos = i ; break ; } } if ( pos == - 1 ) { return 0 ; } int last = 1 ; int ans = 1 ; for ( int i = pos + 1 ; i < n ; i ++ ) { if ( s . charAt ( i ) == '0' ) { if ( last == 1 ) { ans ++ ; last = 0 ; } } else { if ( last == 0 ) { ans ++ ; last = 1 ; } } } return ans ; } public static void main ( String [ ] args ) { String s = "10111" ; System . out . println ( minOperations ( s ) ) ; } }