Home Tutorial Java Core Java Convert decimal to binary using Stacks

 
 

Java Convert decimal to binary using Stacks
Posted on: August 19, 2010 at 12:00 AM
In this section, you will learn how to convert decimal into binary using stacks.

Java Convert decimal to binary using Stacks

In this section, you will learn 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.

Here is the code:

import java.util.*;

public class ConvertDecimalToBinaryUsingStack {
	public static void main(String args[]) {
		Scanner input = new Scanner(System.in);
		System.out.print("Enter the number: ");
		int num = input.nextInt();
		Stack stack = new Stack();

		if (num == 0) {
			System.out.println("BINARY is 0000");
		} else if (num == 1) {
			System.out.println("Binary is: 0001");
		} else {
			while (num != 0) {
				int a = num / 2;
				int b = num % 2;
				stack.push(b);
				num = a;
			}
		}

		while (!stack.empty()) {
			System.out.print(stack.pop());
		}

		System.out.println(" ");
	}
}

Output:

Enter the Number: 123
1111011

Related Tags for Java Convert decimal to binary using Stacks: