> For the complete documentation index, see [llms.txt](https://mayanktyagi3111.gitbook.io/interview-prep/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://mayanktyagi3111.gitbook.io/interview-prep/stacks-and-queues/method-to-generate-binary-numbers-from-1-to-n.md).

# Method to Generate Binary Numbers from 1 to n

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
```

```java
class Solution {
    public void generatePrintBinary(int n) {
        Queue<String> q = new LinkedList<String>();
        q.add("1");
        // Assume "1" as root and '0' append as left child & '1' as right child
        // Now we are just doing level order traversal on this tree
        while (n-- > 0) {
            // print the front of queue
            String s1 = q.poll();
            System.out.println(s1);
            // Appending 0, makes the number twice
            q.add(s1 + "0");
            // Appending 1, makes the number twice + 1
            q.add(s1 + "1");
        }
    }
}
```
