Binary String is a special type of string in which we have only 0 and 1 as characters of the string.
Example: "01101001"
Check whether a given string is binary or not
We will take a string as input from the user. And then check whether a given string is binary or not and return true or false based on this.
Example:
Input: "011000101"
Output: Binary String
To check if the given string is a binary string or not. We will loop over the string and if any element is other than '1' or '0' then it is not a binary string otherwise it is a binary string.
Algorithm:
- Loop over the string, i = 0 to str.length
- if str[i] != '0' or str[i] != '1' -> not binary, break
- Exit
Program to check the whether a given string is binary or not
Output:
Another Approach:
Another approach to solve the problem is by using sets to store the characters of the binary string. We will store '0' and '1' to the set and then compare it with the characters of the string, if there exists any character other than those present in the set return false otherwise return true.
Program to check whether a given string is binary or not
Output:
Explanation:
In the above code, we have taken the string as input from the user. And then created two sets one strSet consisting of elements of the string and other binValues consisting of binary values i.e. 0 and 1. Then we have compared values and return the statements based on the comparison.
need an explanation for this answer? contact us directly to get an explanation for this answer