How to use Arrays In Java

Algorithm

  1. Store the remainder when the number is divided by 2 in an array.
  2. Divide the number by 2
  3. Repeat the above two steps until the number is greater than zero.
  4. Print the array in reverse order now.

The below diagram shows an example of converting the decimal number 17 to an equivalent binary number. 

Java Program to Convert Decimal Number to Binary Using Arrays

Java




// Java program to convert a decimal
// number to binary number
import java.io.*;
  
class GFG 
{
    // function to convert decimal to binary
    static void decToBinary(int n)
    {
        // array to store binary number
        int[] binaryNum = new int[1000];
   
        // counter for binary array
        int i = 0;
        while (n > 0
        {
            // storing remainder in binary array
            binaryNum[i] = n % 2;
            n = n / 2;
            i++;
        }
   
        // printing binary array in reverse order
        for (int j = i - 1; j >= 0; j--)
            System.out.print(binaryNum[j]);
    }
      
    // driver program
    public static void main (String[] args) 
    {
        int n = 17;
          System.out.println("Decimal - " + n);
        System.out.print("Binary - ");
          decToBinary(n);
    }
}


Output

Decimal - 17
Binary - 10001

The complexity of the above method:

Time Complexity: O(log2(n))
Auxiliary Space: O(1000)

Java Program for Decimal to Binary Conversion

Given a decimal number as input, we need to write a program to convert the given decimal number into an equivalent binary number.

Examples: 

Input : 7
Output : 111

Input: 33
Output: 100001

Binary-to-decimal conversion is done to convert a number given in the binary system to its equivalent in the decimal number system. A number system is a format to represent numbers in a certain way. 

Binary Number System – The binary number system is used in computers and electronic systems to represent data, and it consists of only two digits which are 0 and 1. 

Decimal Number System – The decimal number system is the most commonly used number system worldwide, which is easily understandable to people. It consists of digits from 0 to 9.

Similar Reads

Methods For Decimal to Binary Conversion

There are numerous approaches to converting the given decimal number into an equivalent binary number in Java. A few of them are listed below....

1. Using Arrays

Algorithm...

2. Using  Bitwise Operators

...

3. Using Math.pow() method (Without using Arrays)

We can use bitwise operators to do the above job....