Javatpoint Logo
Javatpoint Logo

Java Program to Generate Binary Numbers

In this section, we will create Java programs that generates binary numbers from the specified range (0 to n).

The generation of binary numbers from 1 to n can be achieved through a binary tree. We know that in a tree, every node has two child nodes i.e. right and left nodes. In this binary tree the root node will be 1. In order to get the left and right node of the root node, we will append 0 and 1 respectively at the end of the root node, and so on. Consider the following binary tree for the same.

Java Program to Generate Binary Numbers

Let's follow the steps given below to generate the binary numbers.

  1. Create a Queue of type String.
  2. Initialize a variable say n to 0.
  3. Push 1 to the queue, as it is the root node.
  4. While the total is less than n, repeat steps 6 and 7.
  5. Pop the root element from the queue and print it.
  6. Push its left child (element + 0), and the right child (element + 1) to the queue.
  7. Increment the variable total by 1.

Implement the above approach in a Java program.

GenerateBinaryNumbers.java

Output:

1 10 11 100 101 110 111 
1 10 11 100 101 110 111 1000 1001 1010

Let's see another logic for the same.

Run a loop from 1 to n. Inside the loop, invoke decimal to binary conversion.

  • Create an empty Queue of type String.
  • Add 1 to the queue as the first binary number.
  • Enqueue the first binary number 1 to the queue.
  • Run a loop for generating and printing n binary numbers.
    1. Dequeue and print the front of the queue.
    2. Enqueue the second binary number by appending 0 to the first binary number.
    3. Enqueue the third binary number by appending 1 to the first binary number.

The time and space complexity for the following solution is O(n).

Java Program to Generate Binary Numbers Up to n

Using Queue

GenerateBinaryNumbers.java

Output:

1 10 11 100 101 110 111 1000 1001 1010 1011 1100 1101 1110

Let's see another logic.

In the following Java program, we have not used any data structure. Instead we have used a function itoa(). The function converts integer into null-terminated string. It can convert negative numbers too.

  1. Initialize the value up to which you want to generate binary numbers.
  2. Find the modulo and store the remainder in an array after that divide the number by 2.
  3. Repeat the above step until the number becomes less than or equal to zero.
  4. Print the array from the end to get the equivalent binary numbers.

GenerateBinaryNumbers.java

Output:

0 1 10 11 100 101 110 111 1000 1001 1010






Youtube For Videos Join Our Youtube Channel: Join Now

Feedback


Help Others, Please Share

facebook twitter pinterest

Learn Latest Tutorials


Preparation


Trending Technologies


B.Tech / MCA