Given a number n, write a function that generates and prints all binary numbers with decimal values from 1 to n.
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.
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.
Following is implementation of above algorithm.
// C++ program to generate binary numbers from 1 to n
// This function uses queue data structure to print binary numbers
// Create an empty queue of strings
// Enqueue the first binary number
// This loops is like BFS of a tree with 1 as root
// 0 as left child and 1 as right child and so on
// print the front of queue
string s1 = q.front();
cout << s1 <<
string s2 = s1;
// Store s1 before changing it
// Append "0" to s1 and enqueue it
// Append "1" to s2 and enqueue it. Note that s2 contains
// the previous front
// Driver program to test above function
n = 10;
1 10 11 100 101 110 111 1000 1001 1010
Disclaimer: This does not belong to TechCodeBit, its an article taken from the below
source and credits.
source and credits: http://www.geeksforgeeks.org
We have built the accelerating growth-oriented website for budding engineers and aspiring job holders of technology companies such as Google, Facebook, and Amazon
If you would like to study our free courses you can join us at
http://www.techcodebit.com. #techcodebit #google #microsoft #facebook #interview portal #jobplacements