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