# Count number of binary strings of length N having only 0’s and 1’s in C++

We are given a number let’s say, num and the task is to calculate the count of binary strings that can be formed through the given number num containing only o’s and 1’s.

Binary Number System is one the type of Number Representation techniques. It is most popular and used in digital systems. Binary system is used for representing binary quantities which can be represented by any device that has only two operating states or possible conditions. For example, a switch has only two states: open or close.

In the Binary System, there are only two symbols or possible digit values, i.e., 0 and 1. Represented by any device that only has 2 operating states or possible conditions. Binary strings are those strings that contains binary values i.e. either 0’s or 1’s

## For Example

Input − num = 3
Output − count is 8

Explanation − binary combinations that can be formed of length 3 are:000, 111, 001,101, 100, 110, 011, 010 since they are total 8 in numbers therefore the count is 8.

Input − num = 2
Output − count is 4

Explanation − binary combinations that can be formed of length 2 are:00, 11, 01,10 since they are total 4 in numbers therefore the count is 4.

## Approach used in the below program is as follows

• Input a number of type long long as the number can be any digit long

• Calculate the mod value as (long long)(le9 + 7)

• Create a function to calculate the count

• Declare a temporary variable that will store the count and another variable temp and initialises it with 2.

• Set num as temp = temp % mod

• Start loop while num > 0

• Check IF num & 1 then set count as (count * temp)% mod

• Set num = num >> 1

• Set temp = (temp * temp) % mod

• Return count

• Print the result.

## Example

Live Demo

#include <iostream>
using namespace std;
#define ll long long
#define mod (ll)(1e9 + 7)
// An iterative function to find (x^y)%p in O(log y)
ll power(ll x, ll y, ll p){
ll result = 1;
x = x % p; // Update x if it is more than or
// equal to p
while (y > 0){
// If y is odd, multiply x with result
if (y & 1){
result = (result * x) % p;
}
// y must be even now
y = y >> 1; // y = y/2
x = (x * x) % p;
}
return result;
}
// Function to count the number of binary strings
ll countbstring(ll num){
int count = power(2, num, mod);
return count;
}
int main(){
ll num = 3;
cout <<"count is: "<<countbstring(num);
return 0;
}

## Output

If we run the above code we will get the following output −

count is: 8

Updated on: 15-May-2020

336 Views