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: using System ; using System . Collections . Generic ; class GFG { static int groupsOfOnes ( string S , int N ) { int count = 0 ; Stack < int > st = new Stack < int > ( ) ; for ( int i = 0 ; i < N ; i ++ ) { if ( S [ i ] == '1' ) st . Push ( 1 ) ; else { if ( st . Count > 0 ) { count ++ ; while ( st . Count > 0 ) { st . Pop ( ) ; } } } } if ( st . Count > 0 ) count ++ ; return count ; } public static void Main ( ) { string S = "100110111" ; int N = S . Length ; Console . Write ( groupsOfOnes ( S , N ) ) ; } }