Convert decimal to binary using Stacks in Java

Posted By: Java Examples - 2:08 PM

Share

& Comment

How to convert decimal into binary using stacks. You all are aware of Stacks. It performs two basic operations push and pop. The push operation adds an element to the top of the list, or initializing the stack if it is empty and the pop operation removes an item from the top of the list. Using these operations, we have converted a decimal number into binary.


Java version of this program is given below:
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package stack;

import java.util.Scanner;

/**
 *
 * @author ACHCHUTHAN
 */
public class Decimal2BinaryDemo {

    public static void main(String args[]) {
        Scanner input=new Scanner(System.in);
        System.out.println("Enter decimal number =");
        int num=input.nextInt();
        Stack s4 = new Stack(16);
        int n=num;
        int i = 0;
        while (n > 0) {
            s4.push(n % 2);
            n = n / 2;
            i++;
        }
        s4.print();
        System.out.print(num+" is convert to binary ->");
        while (i > 0) {
            System.out.print(s4.pop()+" ");
            i--;
        }
    }
}

Output of this program :
run:
Enter decimal number =
30
0 | 1 | 1 | 1 | 1 | 
------------------------------------------
Top= 5
30 is convert to binary ->1 1 1 1 0 
BUILD SUCCESSFUL (total time: 2 seconds)

About Java Examples

I’m passionate about Web Development and Programming and I go to extreme efforts to meet my passion. I’m a believer of learning the fundamentals first. I try to understand everything little bit more than the average.

Copyright © 2016 Java Examples ACHCHUTHAN.ORG. Designed by Templateism .