VOOZH about

URL: https://www.geeksforgeeks.org/dsa/1-to-n-bit-numbers-with-no-consecutive-1s-in-binary-representation/

⇱ 1 to n bit numbers with no consecutive 1s in binary representation. - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

1 to n bit numbers with no consecutive 1s in binary representation.

Last Updated : 31 May, 2022

Given a number n, our task is to find all 1 to n bit numbers with no consecutive 1s in their binary representation. 
Examples: 
 

Input : n = 4
Output : 1 2 4 5 8 9 10
These are numbers with 1 to 4
bits and no consecutive ones in
binary representation.

Input : n = 3
Output : 1 2 4 5


 


We add bits one by one and recursively print numbers. For every last bit, we have two choices. 
 

 if last digit in sol is 0 then
 we can insert 0 or 1 and recur. 
 else if last digit is 1 then
 we can insert 0 only and recur.


We will use recursion- 
 

  1. We make a solution vector sol and insert first bit 1 in it which will be the first number.
  2. Now we check whether length of solution vector is less than or equal to n or not.
  3. If it is so then we calculate the decimal number and store it into a map as it store numbers in sorted order.
  4. Now we will have two conditions- 
    • if last digit in sol is 0 the we can insert 0 or 1 and recur.
    • else if last digit is 1 then we can insert 0 only and recur.


 

numberWithNoConsecutiveOnes(n, sol)
{
if sol.size() <= n
 
 // calculate decimal and store it
 if last element of sol is 1
 insert 0 in sol 
 numberWithNoConsecutiveOnes(n, sol)
 else
 insert 1 in sol
 numberWithNoConsecutiveOnes(n, sol)

 // because we have to insert zero 
 // also in place of 1
 sol.pop_back();
 insert 0 in sol
 numberWithNoConsecutiveOnes(n, sol)
 }


 

Output : 
 

1 2 4 5 8 9 10

Time Complexity : O(nlogn)

Auxiliary Space: O(n)


Related Post : 
Count number of binary strings without consecutive 1’s
 

Comment