• Tutorials
  • DSA
  • Data Science
  • Web Tech
  • Courses
June 13, 2022 |1.9K Views

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

  Share   Like
Description
Discussion

Given a string of 0 and 1, we need to check that the given string is valid or not. The given string is valid when there is no zero is present in between 1’s. For example, 1111, 0000111110, 1111000 are valid strings but 01010011, 01010, 101 are not. 


Examples:

Input : 100
Output : VALID

Input : 1110001
Output : NOT VALID
There is 0 between 1s

Suppose we have a string: 01111011110000 Now take two variables say A and B. run a loop for 0 to length of the string and point Ato the first occurrence of 1, after that again run a loop from length of the string to 0and point second variable to the last occurrence of 1.So A = 1 (Position of first ‘1’ is the string) and B = 9 (last occurrence of ‘1’). 

Now run a loop from A to B and check that ‘0’ is present between 1 or not, if “YES” than set flag to 1 and break the loop, else set flag to 0.In this case flag will set to 1 as the given string is not valid and print “NOT VALID”.

Check if a binary string has a 0 between 1s or not : https://www.geeksforgeeks.org/check-binary-string-0-between-1s-not/