Check for Binary String
Last Updated :
23 Nov, 2024
Improve
Try it on GfG Practice
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: trueInput: 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++ 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 Program to check if a string is
// binary string or not
#include <stdio.h>
#include <string.h>
#include <stdbool.h>
bool isBinary(char *s) {
for(int i = 0; i < strlen(s); i++) {
// Check if the character is neither
// '0' nor '1'
if(s[i] != '0' && s[i] != '1') {
return false;
}
}
return true;
}
int main() {
char s[] = "01010101010";
printf(isBinary(s) ? "true" : "false");
return 0;
}
// Java Program to check if a string is
// binary string or not
class GfG {
static boolean isBinary(String s) {
for (int i = 0; i < s.length(); i++) {
// Check if the character is neither
// '0' nor '1'
if (s.charAt(i) != '0' && s.charAt(i) != '1') {
return false;
}
}
return true;
}
public static void main(String[] args) {
String s = "01010101010";
System.out.println(isBinary(s));
}
}
# Python Program to check if a string is
# binary string or not
def isBinary(s):
for i in range(len(s)):
# Check if the character is neither
# '0' nor '1'
if s[i] != '0' and s[i] != '1':
return False
return True
s = "01010101010"
print("true" if isBinary(s) else "false")
// C# Program to check if a string is
// binary string or not
using System;
class GfG {
static 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;
}
static void Main() {
string s = "01010101010";
Console.WriteLine(isBinary(s) ? "true" : "false");
}
}
// JavaScript Program to check if a string is
// binary string or not
function isBinary(s) {
for (let 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;
}
let s = "01010101010";
console.log(isBinary(s));
Output
True
Time Complexity: O(n), where n is the length of input string s.
Auxiliary Space: O(1)