Open In App

Check for Binary String

Last Updated : 23 Nov, 2024
Comments
Improve
Suggest changes
4 Likes
Like
Report

Given a string s, the task is to check if it is a binary string or not. A binary string is a string which only contains the characters '0' and '1'.

Examples:

Input: s = "01010101010"
Output: true

Input: s = "geeks101"
Output: false

Approach:

The idea is to iterate over all the characters of the string and if we encounter a character other than '0' or '1', then the input string is not a binary string. Otherwise, if all the characters are either '0' or '1', then the input string is a binary string.

C++
C Java Python C# JavaScript

Output
True

Time Complexity: O(n), where n is the length of input string s.
Auxiliary Space: O(1)


Article Tags :

Explore