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
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");
        }
    }
}

Last updated