- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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
#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
- Related Articles
- Check if all the 1s in a binary string are equidistant or not in Python
- Check if a string has m consecutive 1s or 0s in Python
- Check if a binary string contains consecutive same or not in C++
- Python - Check if a given string is binary string or not
- Check if a Binary Tree (not BST) has duplicate value in C++
- Check if a binary tree is sorted levelwise or not in C++
- Check if a string follows anbn pattern or not in C++
- A program to check if a binary tree is BST or not in C ?
- Check if a binary string has two consecutive occurrences of one everywhere in C++
- Check if a binary tree is sorted level-wise or not in C++
- Program to check if a matrix is Binary matrix or not in C++
- Program to check if binary string has at most one segment of ones or not using Python
- C# program to check if a string is palindrome or not
- Check if a string is Isogram or not in Python
- Check if it is possible to rearrange a binary string with alternate 0s and 1s in Python

Advertisements