Given a string of integers ‘bin’. Return 'true' if the string represents a valid binary number, else return 'false'. A binary number is a number that has only 0 or 1 in it.
The first line of input contains an integer ‘T’ representing the number of test cases. Then the test cases follow.
The first line of each testcase contains a single string ‘bin’.
Output Format:
For each test case, return a boolean value that is 'true' if the string is binary and 'false' if the string is not binary.
The output for each test case is printed on a separate line.
Note:
You do not need to print anything, it has already been taken care of. Just implement the given function.
1 <= T <= 50
1 <= length(bin) <= 10^4
Where length(bin) is the length of the binary string.
Time Limit: 1 sec
3
1000
20110
101013
YES
NO
NO
Test Case 1:
We see that the given string is “1000”. We can clearly see that all of the string elements are either ‘1’ or ‘0’. Therefore we return true and print YES in a new line.
Test Case 2:
We see that the given string is “20110”. We can clearly see that the first string is not a binary string as the first element of the string is a ‘2’ which is not a binary number. Therefore we return false and print “NO” in a new line.
Test Case 3:
We see that the given string is “101013”. We can clearly see that the first string is not a binary string as the last element of the string is a ‘3’ which is not a binary number. Therefore we return false and print “NO” in a new line.
5
1010111
91102
1010101
000001
122345
YES
NO
YES
YES
NO
Try to find the answer recursively
From the above idea, we can devise the following approach:
isBinaryHelper ( ‘BIN’ , ‘CUR_IDX’ ):
NOTE: This approach will result in a ‘StackOverflow’ error in Java because of excessive memory usage in the recursion stack.
O(N), where ‘N’ is the number of elements in the string.
We need to recursively check each element of the string. Therefore the time complexity is of the order of ‘N’.
O(N), where ‘N’ is the number of elements in the binary string.
Recursive stack uses space of order of ‘N’.