Skip to content
Related Articles

Related Articles

PHP Program to Count number of binary strings without consecutive 1’s
  • Last Updated : 02 Jan, 2019
GeeksforGeeks - Summer Carnival Banner

Given a positive integer N, count all possible distinct binary strings of length N such that there are no consecutive 1’s.

Examples:

Input:  N = 2
Output: 3
// The 3 strings are 00, 01, 10

Input: N = 3
Output: 5
// The 5 strings are 000, 001, 010, 100, 101

Recommended: Please solve it on “PRACTICE ” first, before moving on to the solution.

PHP




<?php
// PHP program to count all distinct
// binary stringswithout two
// consecutive 1's
  
function countStrings($n)
{
    $a[$n] = 0;
    $b[$n] = 0;
    $a[0] = $b[0] = 1;
    for ($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];
}
  
    // Driver Code
    echo countStrings(3) ;
  
// This code is contributed by nitin mittal
?>
Output:
5

Please refer complete article on Count number of binary strings without consecutive 1’s for more details!

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.

My Personal Notes arrow_drop_up
Recommended Articles
Page :