Minimum count of 0 s to be removed from given Binary string to make all 1 s occurs consecutively | C ++ program for the above approach ; Function to find minimum count of 0 s removed from the string S such that all 1 s occurs consecutively ; Stores the first and the last occurrence of 1 ; Iterate over the characters the string , S ; If current character is '1' ; Update fst_occur ; Iterate over the characters the string , S ; If current character is '1' ; Update lst_occur ; Stores the count of 0 s between fst_occur and lst_occur ; Iterate over the characters of S between fst_occur and lst_occur ; If current character is '0' ; Update count ; Print the resultant minimum count ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void makeContiguous ( string S , int N ) { int fst_occur , lst_occur ; for ( int x = 0 ; x < N ; x ++ ) { if ( S [ x ] == '1' ) { fst_occur = x ; break ; } } for ( int x = N - 1 ; x >= 0 ; x -- ) { if ( S [ x ] == '1' ) { lst_occur = x ; break ; } } int count = 0 ; for ( int x = fst_occur ; x <= lst_occur ; x ++ ) { if ( S [ x ] == '0' ) { count ++ ; } } cout << count ; } int main ( ) { string S = "010001011" ; int N = S . size ( ) ; makeContiguous ( S , N ) ; return 0 ; }