Given an integer N, the task is to count the number of binary strings of length N having only 0’s and 1’s.
Note: Since the count can be very large, return the answer modulo 10^9+7.
Explantion: The numbers are 00, 01, 11, 10. Hence the count is 4.
Explantion: The numbers are 000, 001, 011, 010, 111, 101, 110, 100. Hence the count is 8.
Approach: The problem can be easily solved by using Permutation and Combination. At each position of the string there can only be two possibilities, i.e., 0 or 1. Therefore, the total number of permutation of 0 and 1 in a string of length N is given by 2*2*2*…(N times), i.e., 2^N. The answer can be very large, hence modulo by 10^9+7 is returned.
Below is the implementation of the above approach:
// If y is odd, multiply x with result
if ($y & 1)
$res = ($res * $x) % $p;
// y must be even now
$y = $y >> 1; // y = y/2
$x = ($x * $x) % $p;
// Function to count the number of binary
// strings of length N having only 0’s and 1’s
$count = power(2, $N);
// Driver code
$N = 25;
// This code is contributed by Rajput-Ji
- Generate all binary strings of length n with sub-string "01" appearing exactly twice
- Count binary strings with twice zeros in first half
- Number of strings of length N with no palindromic sub string
- Count number of distinct substrings of a given length
- Number of Binary Trees for given Preorder Sequence length
- Count number of strings (made of R, G and B) using given combination
- Count number of trailing zeros in Binary representation of a number using Bitset
- All possible strings of any length that can be formed from a given string
- Print all possible strings of length k that can be formed from a set of n characters
- Count unique subsequences of length K
- Check if a binary string contains all permutations of length k
- Count squares with odd side length in Chessboard
- Count maximum-length palindromes in a String
- Program to add two binary strings
- Find the count of numbers that can be formed using digits 3, 4 only and having length at max N.
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.