Check if a binary string has a 0 between 1 s or not | Set 1 ( General approach ) | C ++ program to check if a string is valid or not . ; Function returns 1 when string is valid else returns 0 ; Find first occurrence of 1 in s [ ] ; Find last occurrence of 1 in s [ ] ; Check if there is any 0 in range ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool checkString ( string s ) { int len = s . length ( ) ; int first = s . size ( ) + 1 ; for ( int i = 0 ; i < len ; i ++ ) { if ( s [ i ] == '1' ) { first = i ; break ; } } int last = 0 ; for ( int i = len - 1 ; i >= 0 ; i -- ) { if ( s [ i ] == '1' ) { last = i ; break ; } } for ( int i = first ; i <= last ; i ++ ) if ( s [ i ] == '0' ) return false ; return true ; } int main ( ) { string s = "00011111111100000" ; checkString ( s ) ? cout << " VALID STRNEWLINE " : cout << " NOT ▁ VALID STRNEWLINE " ; return 0 ; }