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
def minOperations ( s ) : NEW_LINE INDENT n = len ( s ) NEW_LINE pos = - 1 NEW_LINE for i in range ( len ( s ) ) : NEW_LINE INDENT if ( s [ i ] == '1' ) : NEW_LINE INDENT pos = i NEW_LINE break NEW_LINE DEDENT DEDENT if ( pos == - 1 ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT last = 1 NEW_LINE ans = 1 NEW_LINE for i in range ( pos + 1 , n ) : NEW_LINE INDENT if ( s [ i ] == '0' ) : NEW_LINE INDENT if ( last == 1 ) : NEW_LINE INDENT ans += 1 NEW_LINE last = 0 NEW_LINE DEDENT DEDENT else : NEW_LINE INDENT if ( last == 0 ) : NEW_LINE INDENT ans += 1 NEW_LINE last = 1 NEW_LINE DEDENT DEDENT DEDENT return ans NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT s = "10111" NEW_LINE print ( minOperations ( s ) ) NEW_LINE DEDENT