text: Count of groups of consecutive 1 s in a given Binary String | C ++ program for the above approach ; Function to find the number of the groups of 1 s only in the binary string ; Stores number of groups of 1 s ; Initialization of the stack ; Traverse the string S ; If S [ i ] is '1' ; Otherwise ; If st is empty ; If st is not empty ; Return answer ; Driver code ; Input ; Function call
code: #include <bits/stdc++.h> NEW_LINE using namespace std ; int groupsOfOnes ( string S , int N ) { int count = 0 ; stack < int > st ; for ( int i = 0 ; i < N ; i ++ ) { if ( S [ i ] == '1' ) st . push ( 1 ) ; else { if ( ! st . empty ( ) ) { count ++ ; while ( ! st . empty ( ) ) { st . pop ( ) ; } } } } if ( ! st . empty ( ) ) count ++ ; return count ; } int main ( ) { string S = "100110111" ; int N = S . length ( ) ; cout << groupsOfOnes ( S , N ) << endl ; return 0 ; }