- Related Questions & Answers
- Program to Count number of binary strings without consecutive 1’s in C/C++?
- Python Program to Count number of binary strings without consecutive 1’
- Count number of binary strings without consecutive 1's in C
- Count Binary String without Consecutive 1's
- Count number of binary strings of length N having only 0’s and 1’s in C++
- C# program to check if there are K consecutive 1’s in a binary number
- Binary representation of next greater number with same number of 1’s and 0’s in C Program?
- Count the number of 1’s and 0’s in a binary array using STL in C++
- Count subarrays with equal number of 1’s and 0’s in C++
- 1’s and 2’s complement of a Binary Number?
- Count 1’s in a sorted binary array in C++
- Python program to check if there are K consecutive 1’s in a binary number?
- C# program to find the length of the Longest Consecutive 1’s in Binary Representation of a given integer
- Count subarrays consisting of only 0’s and only 1’s in a binary array in C++
- Program to find longest consecutive run of 1 in binary form of a number in C++

- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who

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

#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; }

Advertisements