Open In App

Java Program to Convert a Decimal Number to Binary Number using Stacks

Java is high level, compiled as well as interpreted programming language. Stack is an abstract data type used in most of the programming languages and can be implemented using arrays or linked list. Stack data structure follows the principle of LIFO (Last In First Out) . Stack allows push, pop, peek operations to be performed. The push operation is used to insert a new element into the stack. The pop operation is used to remove an element from the top of the stack. The peek operation is used to get the top element of the stack without removing it from the stack. A decimal number can be converted into binary number using the push and pop operation of the Stack. Now, Java provides inbuilt Stack class which can be used to suit our purpose.

Converting a decimal number to binary number using stacks:



  1. Using predefined stack.
  2. Using array as a stack.

Method 1: Using Predefined Stack

Approach:



Code Implementation:




// Java Program to Convert a Decimal Number
// to Binary Number using Stacks
 
import java.util.*;
public class DecimalToBinary
{
public static void main(String args[])
{
    // creating a stack
    Stack<Integer> stack = new Stack<Integer>();
   
    System.out.println("Enter a decimal number: ");
    int num = 23;
   
    while(num>0)
    {
        int r = num%2;
       
        // pushing the remainder inside the stack
        stack.push(r);
        num/=2;
    }
   
     System.out.print("Binary equivalent: ");
   
     while (!(stack.isEmpty() ))
     {
         // printing the resultant binary number stored in the
         // stack in LIFO manner
         System.out.print(stack.pop());
     }
}
}

Output
Enter a decimal number: 
Binary equivalent: 10111

The time complexity is O(log n), where n is the decimal number.

The auxiliary space is O(log n) as well.

Method 2: Using Array as a stack

Approach:




// Java Program to Convert a Decimal Number
// to Binary Number using Stacks
 
import java.util.*;
public class DecimalToBinary {
    static int arr[] = new int[1000];
 
    // maintaining count variable as the top
    // of the stack
    static int count;
 
    // push at the count index and increment the count
    public static void push(int n) { arr[count++] = n; }
 
    // pop all the elements starting from count-1
    // till 0
    public static void pop()
    {
        for (int i = count - 1; i >= 0; i--) {
            System.out.print(arr[i]);
        }
    }
 
    public static void main(String args[])
    {
        System.out.println("Enter a decimal number: ");
        int num = 46;
 
        while (num > 0) {
            int r = num % 2;
            push(r);
            num /= 2;
        }
 
        System.out.print("Binary equivalent: ");
 
        pop();
    }
}

Output
Enter a decimal number: 
Binary equivalent: 101110

Time complexity: O(logn) as here while loop runs logn times

Auxiliary space: O(1)


Article Tags :