

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Find the number of binary strings of length N with at least 3 consecutive 1s in C++
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
Example
#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); }
Output
The number of binary strings with at least 3 consecutive 1s: 3
- Related Questions & Answers
- Find consecutive 1s of length >= n in binary representation of a number in C++
- Program to find longest consecutive run of 1s in binary form of n in Python
- 1 to n bit numbers with no consecutive 1s in binary representation?
- Count number of binary strings without consecutive 1's in C
- Find row number of a binary matrix having maximum number of 1s in C++
- Find the number of consecutive zero at the end after multiplying n numbers in Python
- Find the row with maximum number of 1s using C++
- Python – Find the sum of Length of Strings at given indices
- Program to find length of longest substring with character count of at least k in Python
- Bitwise AND of N binary strings in C++
- Bitwise OR of N binary strings in C++
- Count number of binary strings of length N having only 0’s and 1’s in C++
- C/C++ Program to Count number of binary strings without consecutive 1’s?
- Find perimeter of shapes formed with 1s in binary matrix in C++
- Program to Count number of binary strings without consecutive 1’s in C/C++?
Advertisements