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.
Following is an interesting method that uses queue data structure to print binary numbers. Thanks to Vivek for suggesting this approach.
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.
1 10 11 100 101 110 111 1000 1001 1010
Time Complexity: O(n * logn)
This article is contributed by Abhishek. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above
Don’t stop now and take your learning to the next level. Learn all the important concepts of Data Structures and Algorithms with the help of the most trusted course: DSA Self Paced. Become industry ready at a student-friendly price.
- Generate all binary strings from given pattern
- Generate all palindromic numbers less than n
- Diameter of a Binary Tree in O(n) [A new method]
- Iterative Method to find Height of Binary Tree
- Iterative Method To Print Left View of a Binary Tree
- Print a Binary Tree in Vertical Order | Set 2 (Map based Method)
- Generate n-bit Gray Codes
- Total number of possible Binary Search Trees and Binary Trees with n keys
- Rearrange numbers in an array such that no two adjacent numbers are same
- Check if a binary tree is subtree of another binary tree | Set 2
- Check if a binary tree is subtree of another binary tree | Set 1
- Binary Tree to Binary Search Tree Conversion
- Diameter of a Binary Tree
- Vertical Sum in a given Binary Tree | Set 1
- 1's and 2's complement of a Binary Number
- Largest BST in a Binary Tree | Set 2
- Duplicate subtree in Binary Tree | SET 2
- Print all K-sum levels in a Binary Tree
- Check whether a given binary tree is perfect or not
- Averages of Levels in Binary Tree