Traverse the string to find the first and last occurrences of '1'
for ( int i = 0 ; i < str . length ( ) ; i ++ ) { if ( str [ i ] == '1' ) { if ( firstOne == -1 ) firstOne = i ; lastOne = i ; } } if ( ( firstOne == -1 ) || ( firstOne == lastOne ) ) { cout << 0 ; return ; }