Last Updated: 7 Jan, 2021

Check if number is Binary

Easy
Asked in companies
VisaDisney + HotstarOracle

Problem statement

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.

Input Format:
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.
Constraints:
1 <= T <= 50
1 <= length(bin) <= 10^4

Where length(bin) is the length of the binary string.

Time Limit: 1 sec

Approaches

01 Approach

  • The key idea is that for a string to be a valid binary number, each value in the string can either be a 1 or a 0. So we just need to check each element of the string and if we find any element which is not a 1 or a 0, we return false.
  • Otherwise, if we have traversed all the characters, and all of them are either ‘0’ or ‘1’ we return true.

 

From the above idea, we can devise the following approach:

 

  1. Call ‘isBinaryHelper ( ‘BIN‘, 0)’ function and store the value returned in a boolean variable ‘ans’.
  2. Return ‘ans’.

 

isBinaryHelper ( ‘BIN’ , ‘CUR_IDX’ ):

 

  1. Base Case: If ‘CUR_IDX’ is the last element of the array:
    • Return ‘true’
  2. If ‘BIN[CUR_IDX]’ is not ‘1’ or ‘0’, then:
    • Then we return ‘false’ immediately.
  3. Otherwise:
    • We recursively call the function for the next element.

 

NOTE: This approach will result in a ‘StackOverflow’ error in Java because of excessive memory usage in the recursion stack.

02 Approach

  • The key idea is that for a string to be a valid binary number, each value in the string can either be a 1 or a 0. So we just need to check each element of the string and if we find any element which is neither 1 nor 0, we return ‘false’.
  • Otherwise, if we have traversed all the characters, and all of them are either ‘0’ or ‘1’ we return ‘true’.

 

From the above idea, we can devise the following approach:

 

  1. Take a variable ‘i’ and iterate through each element of the string and check if ‘BIN[i]’ is either 0 or 1.
  2. If it is not a 0 or 1, then:
    • We break the loop and return false immediately.
  3. If we have successfully traversed the complete string, then:
    • We return true.