Open In App

An Interesting Method to Generate Binary Numbers from 1 to n

Last Updated : 25 May, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

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

Recommended Practice

Naive Method: To solve the problem follow the below idea:

A simple method is to run a loop from 1 to n, and call decimal to binary inside the loop. 

Code-

C++
// C++ program to generate binary numbers from 1 to n
#include <bits/stdc++.h>
using namespace std;


void generatePrintBinary(int n)
{
   for(int i=1;i<=n;i++){
       string str="";
       int temp=i;
       while(temp){
           if(temp&1){str=to_string(1)+str;}
           else{str=to_string(0)+str;}
           
           temp=temp>>1;
       }
       cout<<str<<endl;
   }
}

// Driver code
int main()
{
    int n = 10;

    // Function call
    generatePrintBinary(n);
    return 0;
}
Java
// Java program to generate binary numbers from 1 to n
import java.util.*;

public class Main {

    static void generatePrintBinary(int n) {
        for (int i = 1; i <= n; i++) {
            String str = "";
            int temp = i;
            while (temp != 0) {
                if ((temp & 1) == 1) {
                    str = "1" + str;
                } else {
                    str = "0" + str;
                }
                temp = temp >> 1;
            }
            System.out.println(str);
        }
    }

    // Driver code
    public static void main(String[] args) {
        int n = 10;

        // Function call
        generatePrintBinary(n);
    }
}
Python
# Function to generate binary numbers from 1 to n
def generatePrintBinary(n):
    for i in range(1, n + 1):
        str = ""
        temp = i
        # Convert decimal number to binary number
        while temp:
            if temp & 1:
                str = "1" + str
            else:
                str = "0" + str
            temp >>= 1  # Right shift the bits of temp by 1 position
        print(str)


n = 10

# Function call
generatePrintBinary(n)
C#
// C# program to generate binary numbers from 1 to n
using System;

class GFG {
    static void generatePrintBinary(int n)
    {
        for (int i = 1; i <= n; i++) {
            string str = "";
            int temp = i;
            while (temp != 0) {
                if ((temp & 1) != 0) {
                    str = "1" + str;
                }
                else {
                    str = "0" + str;
                }

                temp = temp >> 1;
            }
            Console.WriteLine(str);
        }
    }

    // Driver code
    static void Main()
    {
        int n = 10;

        // Function call
        generatePrintBinary(n);
    }
}
Javascript
// JavaScript program to generate binary numbers from 1 to n

function generatePrintBinary(n) {
  for (let i = 1; i <= n; i++) {
    let str = "";
    let temp = i;
    while (temp) {
      if (temp & 1) {
        str = "1" + str;
      } else {
        str = "0" + str;
      }

      temp = temp >> 1;
    }
    console.log(str);
  }
}

// Driver code
let n = 10;

// Function call
generatePrintBinary(n);

Output-

1
10
11
100
101
110
111
1000
1001
1010

Time Complexity: O(N*logN),N for traversing from 1 to N and logN for decimal to binary conversion 
Auxiliary Space: O(1)

Generate Binary Numbers from 1 to n using the queue:

Follow the given steps to solve the problem:

  • Create an empty queue of strings 
  • Enqueue the first binary number “1” to the queue. 
  • Now run a loop for generating and printing n binary numbers. 
    • Dequeue and Print the front of queue. 
    • Append “0” at the end of front item and enqueue it. 
    • Append “1” at the end of front item and enqueue it.

Thanks to Vivek for suggesting this approach. 
Below is the implementation of the above approach:

C++
// C++ program to generate binary numbers from 1 to n
#include <bits/stdc++.h>
using namespace std;

// This function uses queue data structure to print binary
// numbers
void generatePrintBinary(int n)
{
    // Create an empty queue of strings
    queue<string> q;

    // Enqueue the first binary number
    q.push("1");

    // This loops is like BFS of a tree with 1 as root
    // 0 as left child and 1 as right child and so on
    while (n--) {
        // print the front of queue
        string s1 = q.front();
        q.pop();
        cout << s1 << "\n";

        string s2 = s1; // Store s1 before changing it

        // Append "0" to s1 and enqueue it
        q.push(s1.append("0"));

        // Append "1" to s2 and enqueue it. Note that s2
        // contains the previous front
        q.push(s2.append("1"));
    }
}

// Driver code
int main()
{
    int n = 10;

    // Function call
    generatePrintBinary(n);
    return 0;
}
Java
// Java program to generate binary numbers from 1 to n

import java.util.LinkedList;
import java.util.Queue;

public class GenerateBNo {
    // This function uses queue data structure to print
    // binary numbers
    static void generatePrintBinary(int n)
    {
        // Create an empty queue of strings
        Queue<String> q = new LinkedList<String>();

        // Enqueue the first binary number
        q.add("1");

        // This loops is like BFS of a tree with 1 as root
        // 0 as left child and 1 as right child and so on
        while (n-- > 0) {
            // print the front of queue
            String s1 = q.peek();
            q.remove();
            System.out.println(s1);

            // Store s1 before changing it
            String s2 = s1;

            // Append "0" to s1 and enqueue it
            q.add(s1 + "0");

            // Append "1" to s2 and enqueue it. Note that s2
            // contains the previous front
            q.add(s2 + "1");
        }
    }

    // Driver code
    public static void main(String[] args)
    {
        int n = 10;

        // Function call
        generatePrintBinary(n);
    }
}
// This code is contributed by Sumit Ghosh
Python
# Python3 program to generate binary numbers from
# 1 to n

# This function uses queue data structure to print binary numbers


def generatePrintBinary(n):

    # Create an empty queue
    from queue import Queue
    q = Queue()

    # Enqueue the first binary number
    q.put("1")

    # This loop is like BFS of a tree with 1 as root
    # 0 as left child and 1 as right child and so on
    while(n > 0):
        n -= 1
        # Print the front of queue
        s1 = q.get()
        print(s1)

        # Append "0" to s1 and enqueue it
        q.put(s1+"0")

        # Append "1" to s1 and enqueue it. 
        q.put(s1+"1")


# Driver code
if __name__ == "__main__":
    n = 10

    # Function call
    generatePrintBinary(n)

# This code is contributed by Nikhil Kumar Singh(nickzuck_007)
C#
// C# program to generate binary
// numbers from 1 to n
using System;
using System.Collections.Generic;

class GFG {
    // This function uses queue data
    // structure to print binary numbers
    public static void generatePrintBinary(int n)
    {
        // Create an empty queue of strings
        LinkedList<string> q = new LinkedList<string>();

        // Enqueue the first binary number
        q.AddLast("1");

        // This loops is like BFS of a tree
        // with 1 as root 0 as left child
        // and 1 as right child and so on
        while (n-- > 0) {
            // print the front of queue
            string s1 = q.First.Value;
            q.RemoveFirst();
            Console.WriteLine(s1);

            // Store s1 before changing it
            string s2 = s1;

            // Append "0" to s1 and enqueue it
            q.AddLast(s1 + "0");

            // Append "1" to s2 and enqueue it.
            // Note that s2 contains the previous front
            q.AddLast(s2 + "1");
        }
    }

    // Driver Code
    public static void Main(string[] args)
    {
        int n = 10;

        // Function call
        generatePrintBinary(n);
    }
}

// This code is contributed by Shrikant13
Javascript
<script>

// JavaScript program to generate binary numbers from 1 to n

// This function uses queue data structure to print binary
// numbers
function generatePrintBinary(n)
{
    // Create an empty queue of strings
    var q = [];

    // Enqueue the first binary number
    q.push("1");

    // This loops is like BFS of a tree with 1 as root
    // 0 as left child and 1 as right child and so on
    while (n--) {
        // print the front of queue
        var s1 = q[0];
        q.shift();
        document.write( s1 + "<br>");

        var s2 = s1; // Store s1 before changing it

        // Append "0" to s1 and enqueue it
        q.push(s1+"0");

        // Append "1" to s2 and enqueue it. Note that s2
        // contains the previous front
        q.push(s2+"1");
    }
}

// Driver program to test above function
var n = 10;
generatePrintBinary(n);

</script>

Output
1
10
11
100
101
110
111
1000
1001
1010

Time Complexity: O(N) 
Auxiliary Space: O(N) as extra space is required in this method



Previous Article
Next Article

Similar Reads

Generate a list of n consecutive composite numbers (An interesting method)
Given a number n, generate a list of n composite numbers.Examples: Input : 5 Output : 122, 123, 124, 125 Input : 10 Output : 3628802, 3628803, 3628804, 3628805, 3628806, 3628807, 3628808, 3628809, 3628810 The idea here is using the properties of [Tex]n! [/Tex]. Since [Tex]n! = 1\times2\times3....(n-1)\times n [/Tex], then numbers [Tex]1, 2, 3.....
4 min read
Find Two Missing Numbers | Set 1 (An Interesting Linear Time Solution)
Given an array of n unique integers where each element in the array is in the range [1, n]. The array has all distinct elements and the size of the array is (n-2). Hence Two numbers from the range are missing from this array. Find the two missing numbers. Examples : Input : arr[] = {1, 3, 5, 6} Output : 2 4 Input : arr[] = {1, 2, 4} Output : 3 5 In
15 min read
An interesting solution to get all prime numbers smaller than n
This approach is based on Wilson's theorem and uses the fact that factorial computation can be done easily using DP Wilson's theorem says if a number k is prime then ((k-1)! + 1) % k must be 0. Below is a Python implementation of the approach. Note that the solution works in Python because Python supports large integers by default therefore factori
3 min read
Interesting facts about Fibonacci numbers
We know Fibonacci number, Fn = Fn-1 + Fn-2. First few Fibonacci numbers are 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, .... . Here are some interesting facts about Fibonacci number : 1. Pattern in Last digits of Fibonacci numbers : Last digits of first few Fibonacci Numbers are : 0, 1, 1, 2, 3, 5, 8, 3, 1, 4, 5, 9, 4, 3, 7, 0
15+ min read
Generate all binary numbers in range [L, R] with same length
Given two positive integer numbers L and R. The task is to convert all the numbers from L to R to binary number. The length of all binary numbers should be same. Examples: Input: L = 2, R = 4Output:010011100Explanation: The binary representation of the numbers: 2 = 10, 3 = 11 and 4 = 100.For the numbers to have same length one preceding 0 is added
6 min read
Multiples of 4 (An Interesting Method)
Given a number n, the task is to check whether this number is a multiple of 4 or not without using +, -, * ,/ and % operators.Examples : Input: n = 4 Output - Yes n = 20 Output - Yes n = 19 Output - No Basic Approach:Method 1 (Using XOR) If n is equal to 1 return false.Run a loop from 1 to n and find XOR of all numbers.If the result is equal to n,
8 min read
Iteratively Reverse a linked list using only 2 pointers (An Interesting Method)
Given pointer to the head node of a linked list, the task is to reverse the linked list. Examples: Input : Head of following linked list 1-&gt;2-&gt;3-&gt;4-&gt;NULL Output : Linked list should be changed to, 4-&gt;3-&gt;2-&gt;1-&gt;NULL Input : Head of following linked list 1-&gt;2-&gt;3-&gt;4-&gt;5-&gt;NULL Output : Linked list should be changed
13 min read
An interesting method to print reverse of a linked list
We are given a linked list, we need to print the linked list in reverse order.Examples: Input : list : 5-&gt; 15-&gt; 20-&gt; 25 Output : Reversed Linked list : 25-&gt; 20-&gt; 15-&gt; 5Input : list : 85-&gt; 15-&gt; 4-&gt; 20 Output : Reversed Linked list : 20-&gt; 4-&gt; 15-&gt; 85Input : list : 85Output : Reversed Linked list : 85For printing a
7 min read
Interesting interview question on hashCode and equals method
Prerequisite: Equal and Hashcode Methods in Java , Why to override equal and hashcode methods hashCode and equals method are frequently asked in Java interviews. In general, we do not override both methods but there are some scenarios/requirements when we have to override these two methods. One such scenario when we store user-defined objects in Co
4 min read
Some interesting shortest path questions | Set 1
Question 1: Given a directed weighted graph. You are also given the shortest path from a source vertex 's' to a destination vertex 't'. If weight of every edge is increased by 10 units, does the shortest path remain same in the modified graph? The shortest path may change. The reason is, there may be different number of edges in different paths fro
3 min read
Article Tags :
Practice Tags :
three90RightbarBannerImg