- Related Questions & Answers
- Find consecutive 1s of length >= n in binary representation of a number in C++
- 1 to n bit numbers with no consecutive 1s in binary representation?
- Count number of binary strings without consecutive 1's in C
- Bitwise AND of N binary strings in C++
- Bitwise OR of N binary strings in C++
- C/C++ Program to Count number of binary strings without consecutive 1’s?
- Count number of binary strings of length N having only 0’s and 1’s in C++
- 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’
- Convert a number of length N such that it contains any one digit at least 'K' times in C++
- C# program to find the length of the Longest Consecutive 1’s in Binary Representation of a given integer
- Probability of getting at least K heads in N tosses of Coins in C++
- Count divisors of n that have at-least one digit common with n in Java
- Get at least x number of rows in MySQL?
- Largest Number At Least Twice of Others in Python

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

Suppose, we have an integer N, We have to find the number of all possible distinct binary strings of the length N, which have at least three consecutive 1s. So if n = 4, then the numbers will be 0111, 1110, 1111, so output will be 3.

To solve this, we can use the Dynamic programming approach. So DP(i, x) indicates number of strings of length i with x consecutive 1s in position i + 1 to i + x. Then the recurrence relation will be like −

DP(i, x) = DP(i – 1, 0) + DP(i – 1, x + 1).

The recurrence is based on the fact, that either the string can have 0 or 1 present at position i.

- If it has 0, at ith index then for (i – 1)th position value of x = 0
- If it has 1, at ith index then for (i – 1)th position value of x = 1 + value of x at position i

#include<iostream> using namespace std; int n; int numberCount(int i, int x, int table[][4]) { if (i < 0) return x == 3; if (table[i][x] != -1) return table[i][x]; table[i][x] = numberCount(i - 1, 0, table); table[i][x] += numberCount(i - 1, x + 1, table); return table[i][x]; } int main() { n = 4; int table[n][4]; for (int i = 0; i < n; i++) for (int j = 0; j < 4; j++) table[i][j] = -1; for (int i = 0; i < n; i++) { table[i][3] = (1 << (i + 1)); } cout << "The number of binary strings with at least 3 consecutive 1s: " << numberCount(n - 1, 0, table); }

The number of binary strings with at least 3 consecutive 1s: 3

Advertisements