
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Generate Binary Numbers from 1 to N
Here we will see one interesting method for generating binary numbers from 1 to n. Here we are using queue. Initially the queue will hold first binary number ‘1’. Now repeatedly delete element from queue, and print it, and append 0 at the end of the front item, and append 1 at the end of the front time, and insert them into the queue. Let us see the algorithm to get the idea.
Algorithm
genBinaryNumbers(n)
Begin define empty queue. insert 1 into the queue while n is not 0, do delete element from queue and store it into s1 print s1 s2 := s1 insert s1 by adding 0 after it into queue insert s1 by adding 1 after it into queue decrease n by 1 done End
Example
#include#include using namespace std; void genBinaryNumbers(int n){ queue qu; qu.push("1"); while(n != 0){ string s1 = qu.front(); qu.pop(); cout Output
1 10 11 100 101 110 111 1000 1001 1010 1011 1100 1101 1110 1111
Advertisements