×

Java Program to generate binary numbers

A binary tree can create binary numbers ranging from 1 to n. Every node in a tree, the right, and left nodes, has two children, as is common knowledge. The root node in this binary tree will be 1. We will append 0 and 1 to the end of the root node, respectively, to acquire the left and right nodes of the root node, and so on.

Steps in generating binary numbers

  1. Make a String-type Queue.
  2. Set the value of a variable, say n, to 0.
  3. As the root node, push number one into the queue.
  4. Repeat steps 6 and 7 until the sum is less than n.
  5. Print the root element by selecting it from the queue.
  6. Send the element's right child, as well as its left child, to the queue.
  7. Add one more to the variable total.

Program to generate binary numbers using queues

BinaryUsingQueues.java

import java.util.*; 
public class BinaryUsingQueues 
{  
private static void BinaryNumbersgenerator ( int n )   
{  
    // it returns 0 if number is equal to zero
if ( n == 0 )   
{  
return;  
}  
 // Creating queue of string datatype  
Queue < String > q = new LinkedList < > ( ) ;  
 // Adding a base number to the string
q . add ( " 1 " ) ;  
 // t variable to store the value
int t = 0;  
System.out.println("Binary number for "+n);
while (t < n)   
{  
String curr = q . poll ( ) ;  
System . out. print ( curr + " " ) ;  
q . add ( curr + "0" ) ;  
q . add ( curr + "1" ) ;  
t++;  
}  
System.out.println();  
}  
// Main section of the program where execution starts
public static void main(String args[])   
{  
int n1;
Scanner sc=new Scanner ( System . in ) ;
System.out.println("enter number");
n1 = sc . nextInt ( ) ;
BinaryNumbersgenerator ( n1 ) ;  
int n2 ;
System.out.println("enter number");
n2 = sc . nextInt ( ) ;
BinaryNumbersgenerator ( n2 ) ;  
}  
}  

Output

Java Program to generate binary numbers

Let’s see another approach for the same.

BinaryNumbers2.java

import java. util . * ;  
public class BinaryNumbers2  
{  
public static void main ( String args [ ] )   
{  
int n ;
Scanner sc=new Scanner ( System . in ) ;
System . out . println ( " Enter number " ) ;
n = sc . nextInt ( ) ;
Queue < String > que = new LinkedList <> ( ) ;  
que . add ( " 1 " ) ;  
while (n > 0)   
{  
String t = que . poll ( ) ;  
System . out . print ( t + " " ) ;  
que . add ( t + "0" ) ;  
que . add ( t + " 1 ") ;  
n-- ;  
}  
que . clear ( ) ;  
}  
}

Output

Java Program to generate binary numbers

Binary Numbers using the itoa() method

The function changes an integer into a string with a null termination. Even negative numbers can be converted.

Procedure using the itoa() method

1. Initialize the value up to which binary numbers should be generated.

2. Divide the amount by 2 after calculating the modulo and storing the residual in an array.

3. Till the amount is equal to or less than 0, repeat the previous step.

4. To obtain the equivalent binary numbers, print the array starting at the end.

import java . io . * ;
import java . util . * ;
public class BinaryNumberUsingitoa  
{  
static String itoa ( int x , int base )  
{  
boolean neg = false ;  
String s1 = "";  
if (x == 0)  
return "0";  
neg = (x < 0);  
if (neg)  
x = -1 * x;  
while (x != 0)  
{  
s1 = (x % base) + s1 ;  
x = x / base ;  
}  
if ( neg )  
s1 = "-" + s1 ;  
return s1 ;  
}  
static void Generator ( int n )  
{  
System . out . print ( " 0 " ) ;  
for (int j = 1; j <= n; j++)  
{  
String a1 = new String ( itoa ( j , 2 ) ) ;  
System . out . print ( a1 . substring ( 0 , a1 . length ( ) ) + " " ) ;  
}  
}  
public static void main ( String args [ ] )  
{
Scanner sc = new Scanner ( System. in ) ;
int n1 = sc . nextInt ( ) ;  
Generator ( n1 ) ;  
}  
}  

Output

Java Program to generate binary numbers

Related Topics

Java Program to Add Digits Until the Number Becomes a Single Digit Number

We will develop Java programme that increase a number's digit count in order to reduce it to one. The issue is also known as the digit root problem. Example Consider the case where...

3 minutes read.

Vector in Java

Java Vector Class The Vector class is a legacy class that implements a growable array of objects. The components that it contains can be accessed using an integer index. The size of...

26 minutes read.

How to Iterate a HashMap in Java?

Hash-map is a class of Java collections framework which has the functionality to implement the Map interface of Java. It stores the data in key-value pairs and can be accessed...

5 minutes read.

Block Swap Algorithm for array rotation in Java

An array and r, the rotation factor by which the array must be rotated, are both provided to us. We must then return the rotated array. A well-known and popular method is...

4 minutes read.

Ramanujan Number or Taxicab Number in Java

In this section, we will discuss what a Ramanujan number (also known as a Hardy-Ramanujan number) is and how to use a Java programme to determine if a given integer...

3 minutes read.

Differences between Lock and Monitor in Java Concurrency

In this tutorial, we will discuss the overview of Lock and Monitor and the differences between them. Introduction Java Concurrency is the ability to perform specific tasks at a time parallelly. The...

4 minutes read.

Java Read File to String

There are different ways to deal with forming and examining a text record. This is normal while dealing with various applications. There are different ways to deal with looking at a...

6 minutes read.

How to Compare Two Strings in Java

How to Compare Two Strings in Java On the basis of reference or content, one can compare two strings in Java. String comparison is used in reference matching (== operator), sorting...

4 minutes read.

Map of Map in Java

The map is now a Java interface for mapping keys to values. It is frequently necessary to use Map of Map (nested Map). Nested Maps are useful in various situations, including...

3 minutes read.

Java Integer equals() method

The equals() method of Integer class compares the given object to the specified object. Syntax public boolean equals(Object obj) Parameters The parameter ‘obj’ represents the object to be compared with. Overrides The equals() method overrides equals...

1 minute read.

Longest Arithmetic Progression Sequence in Java

The task is to find the length of the largest sequence in an array to form an arithmetic progression. The array arr[] is given. Longest Arithmetic Progression Sequence in Java Algorithm set...

5 minutes read.

Java concurrency interview questions

During technical interviews, one of the most challenging and sophisticated subjects is concurrency in Java. This page offers responses to some of the related interview questions you might come across. 1....

11 minutes read.

Producer Consumer Problem in Java Using Synchronized Block

The producer-consumer dilemma is a well-known instance of a multi-process synchronization issue in computing. Two processes—the producer and the consumer—are described in the issue, and they share a single, fixed-size...

4 minutes read.

Lombok Java

What is Lombok java? A well-liked and widely-used Java framework that is used to reduce or eliminate boilerplate code is called Project Lombok. Both time and effort are saved. We may...

7 minutes read.

How to Convert Date to Timestamp in Java

How to Convert Date to Timestamp in Java You can convert Date to Timestamp by using the getTime() method of Date class. It returns the long millisecond from Epoch which can...

1 minute read.

Advanced Java Viva Questions

One of the more difficult languages available now is Java. Currently, 10 thousand developers worldwide use the programming language, which is rising daily. So, if you're a Java developer, an aspiring...

9 minutes read.

Memory Leak in Java

Java offers memory management right out of the box. When we use the new keyword to create an object, the JVM initialises for that object immediately. The trash collector automatically...

3 minutes read.

Binary Search Java

Binary search is a search mechanism for key elements from the given List/Array. In Binary search, the search mechanism is followed by dividing the array into parts; hence the search...

3 minutes read.

Java Double Keyword

In java primitive data types, we have two different types of data types which are Boolean and floating-point data types.In floating data type again we have four types which are...

3 minutes read.

public static void main string args meaning in java

In java main() method is the initial point for execution of the program. If a program doesn’t contain the main method, the program will not execute. JVM(java virtual machine) starts...

3 minutes read.