Open In App

Check for Binary String

Last Updated : 23 Nov, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Share
Report
News Follow

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++ Program to check if a string is
// binary string or not

#include <iostream>
using namespace std;

bool isBinary(string &s) {
    for (int i = 0; i < s.length(); i++) {

        // Check if the character is neither
        // '0' nor '1'
        if (s[i] != '0' && s[i] != '1') {
            return false;
        }
    }
    return true;
}

int main() {
    string s = "01010101010";
    cout << (isBinary(s) ? "true" : "false");
    return 0;
}
C Java Python C# JavaScript

Output
True

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


Next Article
Article Tags :
Practice Tags :

Similar Reads

three90RightbarBannerImg