In this tutorial, we will explore how to determine if a given sequence of characters is a binary string. A binary string consists only of the characters ‘0’ and ‘1’. We will solve this problem using both C++ and Python.
Problem Statement
Given a non-empty sequence of characters str
, return true
if the sequence is binary, else return false
.
Examples
Example 1:
Input:
str = "101"
Output:
1
Explanation:
Since the string contains only '0' and '1', the output is 1.
Example 2:
Input:
str = "75"
Output:
0
Explanation:
Since the string contains digits other than '0' and '1', the output is 0.
Requirements
- Function:
isBinary(str: str) -> int
- Input: A string
str
- Output: Return
1
if the string is binary, otherwise return0
.
Constraints
1 <= T <= 50
1 <= Length of str <= 10000
Approach
- Input Handling: Ensure the function takes a string as input.
- Character Check: Iterate through each character in the string and check if it is either ‘0’ or ‘1’.
- Return Result: If all characters are ‘0’ or ‘1’, return
1
. Otherwise, return0
.
Solution in C++
Here is the C++ implementation of the function:
#include <iostream>
#include <string>
using namespace std;
int isBinary(string str) {
for (char c : str) {
if (c != '0' && c != '1') {
return 0;
}
}
return 1;
}
int main() {
int T;
cout << "Enter number of test cases: ";
cin >> T;
while (T--) {
string str;
cout << "Enter the string: ";
cin >> str;
cout << isBinary(str) << endl;
}
return 0;
}
Solution in Python
Here is the Python implementation of the function:
pythonCopy codedef isBinary(s):
for char in s:
if char not in '01':
return 0
return 1
# Main driver code
if __name__ == "__main__":
T = int(input("Enter number of test cases: "))
for _ in range(T):
s = input("Enter the string: ")
print(isBinary(s))
Explanation
- Input Handling: In both implementations, we start by reading the number of test cases. For each test case, we read the input string.
- Character Check: We iterate through each character of the string. If any character is not ‘0’ or ‘1’, we return
0
. If all characters are valid, we return1
. - Output: The output for each test case is printed on a new line.
Time and Space Complexity
- Time Complexity:
O(n)
wheren
is the length of the string. We iterate through the string once. - Space Complexity:
O(1)
since we only use a few extra variables and no additional data structures proportional to the input size.
By following this tutorial, you should be able to understand the fundamental concepts behind checking if a string is binary and how to implement it in both C++ and Python.