Given a positive number n, efficiently generate binary numbers between 1 and n using the queue data structure in linear time.

For example, for n = 16, the binary numbers are:

1 10 11 100 101 110 111 1000 1001 1010 1011 1100 1101 1110 1111 10000

Practice this problem

Following is the C++, Java, and Python implementation:

C++


Download  Run Code

Java


Download  Run Code

Python


Download  Run Code

Output:
 
1 10 11 100 101 110 111 1000 1001 1010 1011 1100 1101 1110 1111 10000

 
The time complexity of the above solution is O(n) and requires O(n) extra space.

 
We can also use std::bitset in C++, as shown below:

C++


Download  Run Code

Output:

00000001 00000010 00000011 00000100 00000101 00000110 00000111 00001000
00001001 00001010 00001011 00001100 00001101 00001110 00001111 00010000

The time complexity of the above solution is O(n), and the auxiliary space used by the program is O(1).