C/C++ Program to Count number of binary strings without consecutive 1’s?

CC++Server Side ProgrammingProgramming

A binary number is a number that contains only two i.e. has one or two. Every binary number is A stream of binary bit, and we consider this as a binary string. for this string, we need to find the number of binary string that does not contain consecutive ones That are of N bits.

For example, for N - 5 the binary strings satisfy the given constraints are 00000 00001 00010 00100 00101 01000 01001 01010 10000 10001 10010 10100 10101

One method is to generate all N-digit strings and print only those strings that satisfy the given constraints. But this method is not that efficient when it comes to working.

The other method is to use recursion. At each point in the recursion, we append 0 and 1 to the partially formed number and recur with one less digit. The trick here is that we append 1 and recur only if the last digit of the partially formed number is 0, That way, we will never have any consecutive 1's in the output string.

Input: n = 5
Output: Number of 5-digit binary strings without any consecutive 1's are 13

Example

#include <iostream>
#include <string>
using namespace std;
int countStrings(int n, int last_digit) {
   if (n == 0)
      return 0;
   if (n == 1) {
      if (last_digit)
         return 1;
      else
         return 2;
   }
   if (last_digit == 0)
      return countStrings(n - 1, 0) + countStrings(n - 1, 1);
   else
      return countStrings(n - 1, 0);
}
int main() {
   int n = 5;
   cout << "Number of " << n << "-digit binary strings without any "
   "consecutive 1's are " << countStrings(n, 0);
   return 0;
}
raja
Published on 19-Aug-2019 11:12:24
Advertisements