# Check if given number contains only ‚Äú01‚Äù and ‚Äú10‚Äù as substring in its binary representation

In this article, we delve into an interesting problem from the world of binary string manipulation: "Check if a given number contains only '01' and '10' as substrings in its binary representation". This problem challenges us to verify whether a number's binary representation contains only the substrings '01' and '10'. We'll discuss the problem in detail, offer a C++ code implementation, and illustrate the concept with an example.

## Understanding the Problem Statement

Given a number, the task is to check if its binary representation contains only '01' and '10' as substrings. In other words, we need to verify if the binary representation of a given number consists of alternating 0s and 1s.

## Approach

A simple way to solve this problem is to convert the number into its binary representation and then check if the binary string contains any '00' or '11' substring. If it does, then the binary representation does not consist of only '01' and '10' substrings. If it doesn't, then it does.

### Example

Let's implement this approach in C++ ‚àí

#include<bits/stdc++.h>
using namespace std;

bool checkBinary(int n) {
string binary = bitset<32>(n).to_string();
return binary.find("00") == string::npos && binary.find("11") == string::npos;
}

int main() {
int n = 5;
if (checkBinary(n)) {
cout << "The binary representation of " << n << " contains only '01' and '10' substrings.";
} else {
cout << "The binary representation of " << n << " does not contain only '01' and '10' substrings.";
}
return 0;
}


### Output

The binary representation of 5 does not contain only '01' and '10' substrings.


This code first converts the number into its binary representation using the bitset function. It then checks if this binary string contains any '00' or '11' substring using the find function.

## Test Case

Let's consider the number 5. Its binary representation is '101'. As you can see, it contains only '01' and '10' as substrings. Therefore, the output of the code will be: "The binary representation of 5 contains only '01' and '10' substrings."

## Conclusion

This article provided an insight into the problem of checking if a given number's binary representation contains only '01' and '10' substrings. The problem, although seemingly complex, simplifies when approached methodically. We discussed a strategy to solve the problem, implemented the approach in C++, and explained the concept with a practical example.

Updated on: 17-May-2023

107 Views 