Method to Generate Binary Numbers

Given a number n, write a function that generates and prints all binary numbers with decimal values from 1 to n.

Examples:

Input: n = 2
Output: 1, 10

Input: n = 5
Output: 1, 10, 11, 100, 101

A simple method is to run a loop from 1 to n, call decimal to binary inside the loop.

Generate binary number

Following is an interesting method that uses queue data structure to print binary numbers.

1) Create an empty queue of strings
2) Enqueue the first binary number “1” to queue.
3) Now run a loop for generating and printing n binary numbers.
a) Dequeue and Print the front of queue.
b) Append “0” at the end of front item and enqueue it.
c) Append “1” at the end of front item and enqueue it.

[ad type=”banner”]

Python Programming Method to Generate Binary Numbers

[pastacode lang=”python” manual=”%23%20Python%20program%20to%20generate%20binary%20numbers%20from%20%0A%23%201%20to%20n%20%0A%20%0A%23%20This%20function%20uses%20queu%20data%20structure%20to%20print%20binary%20numbers%0Adef%20generatePrintBinary(n)%3A%0A%20%20%20%20%20%0A%20%20%20%20%23%20Create%20an%20empty%20queue%0A%20%20%20%20from%20Queue%20import%20Queue%0A%20%20%20%20q%20%3D%20Queue()%0A%20%20%20%20%20%0A%20%20%20%20%23%20Enqueu%20the%20first%20binary%20number%0A%20%20%20%20q.put(%221%22)%0A%20%0A%20%20%20%20%23%20This%20loop%20is%20like%20BFS%20of%20a%20tree%20with%201%20as%20root%0A%20%20%20%20%23%200%20as%20left%20child%20and%201%20as%20right%20child%20and%20so%20on%0A%20%20%20%20while(n%3E0)%3A%0A%20%20%20%20%20%20%20%20n-%3D%201%0A%20%20%20%20%20%20%20%20%23%20Print%20the%20front%20of%20queue%0A%20%20%20%20%20%20%20%20s1%20%3D%20q.get()%20%0A%20%20%20%20%20%20%20%20print%20s1%20%0A%20%20%20%20%20%0A%20%20%20%20%20%20%20%20s2%20%3D%20s1%20%23%20Store%20s1%20before%20changing%20it%0A%20%20%20%20%20%0A%20%20%20%20%20%20%20%20%23%20Append%20%220%22%20to%20s1%20and%20enqueue%20it%0A%20%20%20%20%20%20%20%20q.put(s1%2B%220%22)%0A%20%0A%20%20%20%20%20%20%20%20%23%20Append%20%221%22%20to%20s2%20and%20enqueue%20it.%20Note%20that%20s2%0A%20%20%20%20%20%20%20%20%23%20contains%20the%20previous%20front%0A%20%20%20%20%20%20%20%20q.put(s2%2B%221%22)%0A%20%20%20%20%20%0A%20%0A%23%20Driver%20program%20to%20test%20above%20function%0An%20%3D%2010%0AgeneratePrintBinary(n)%0A%20%0A%0A” message=”” highlight=”” provider=”manual”/]

Output:

1
10
11
100
101
110
111
1000
1001
1010
[ad type=”banner”]

Categorized in: