Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
46 changes: 46 additions & 0 deletions CountNumberOfBinaryWithoutConsecutive1s.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
/**
* Given a positive integer N, count all possible distinct binary strings of length N such that there are no consecutive 1’s.
*
* Input: N = 3
* Output: 5
* The 5 strings are 000, 001, 010, 100, 101
*
* It is really a straight up fibonacci series with values
* 1,2,3,5,8,13....
* Look how we assign a[i] value of a[i-1] + b[i-1] and then b[i] becomes a[i]
*/
public class CountNumberOfBinaryWithoutConsecutive1s {

public int count(int n){
int a[] = new int[n];
int b[] = new int[n];

a[0] = 1;
b[0] = 1;

for(int i=1; i < n; i++){
a[i] = a[i-1] + b[i-1];
b[i] = a[i-1];
}

return a[n-1] + b[n-1];
}

public int countSimple(int n){
int a = 1;
int b = 1;

for(int i=1; i < n; i++){
int tmp = a;
a = a + b;
b = tmp;
}

return a + b;
}

public static void main(String args[]){
CountNumberOfBinaryWithoutConsecutive1s cnb = new CountNumberOfBinaryWithoutConsecutive1s();
System.out.println(cnb.count(3));
}
}