Check if a binary string has a 0 between 1s or not in C++


Here we will see one interesting problem. We have to check whether a string has 0 in between a 1s or not. If not, then the string is valid, otherwise invalid.Suppose there are three strings −

  • 10001111010
  • 00001111100
  • 01111101111

From these three strings, only B is valid, because there is no 0 inside the stream of 1s

To solve this problem, we will find the index of first 1 present in the string, and also find the index of the last 1. Then we will check, is there any 0 from these two indices, if so, then return false, otherwise true (as valid)

Example

 Live Demo

#include <iostream>
using namespace std;
bool hasZeroInOnes(string str) {
   int first, last;
   for(first = 0; first < str.length(); first++){
      if(str[first] == '1')
      break;
   }
   for(last = str.length() - 1; last >= 0; last--){
      if(str[last] == '1')
      break;
   }
   for(int i = first+1; i < last; i++){
      if(str[i] == '0')
      return false;
   }
   return true;
}
int main() {
   string str = "00001111100";
   if(hasZeroInOnes(str)){
      cout << str << " is a valid string";
   } else {
      cout << str << " is NOT a valid string";
   }
}

Output

00001111100 is a valid string

Updated on: 25-Sep-2019

109 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements