 # Convert a decimal into a binary number using stack.

This example shows how to convert decimal number into a binary number using stack.

 ```package com.java2novice.ds.stack; public class MyDecimalToBinary { public static String convertDecialToBinary(int number){ StringBuilder binary = new StringBuilder(); MyDynamicStack stack = new MyDynamicStack(10); if(number == 0){ binary.append("0"); } else { while(number != 0){ stack.push(number%2); number = number/2; } } while(!stack.isStackEmpty()){ try { binary.append(stack.pop()); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } return binary.toString(); } public static void main(String a[]){ System.out.println("Binary value of 2 is: "+convertDecialToBinary(2)); System.out.println("Binary value of 15 is: "+convertDecialToBinary(15)); System.out.println("Binary value of 23 is: "+convertDecialToBinary(23)); } } class MyDynamicStack { private int stackSize; private int[] stackArr; private int top; /** * constructor to create stack with size * @param size */ public MyDynamicStack(int size) { this.stackSize = size; this.stackArr = new int[stackSize]; this.top = -1; } /** * This method adds new entry to the top * of the stack * @param entry * @throws Exception */ public void push(int entry){ if(this.isStackFull()){ System.out.println(("Stack is full. Increasing the capacity.")); this.increaseStackCapacity(); } System.out.println("Adding: "+entry); this.stackArr[++top] = entry; } /** * This method removes an entry from the * top of the stack. * @return * @throws Exception */ public int pop() throws Exception { if(this.isStackEmpty()){ throw new Exception("Stack is empty. Can not remove element."); } int entry = this.stackArr[top--]; //System.out.println("Removed entry: "+entry); return entry; } /** * This method returns top of the stack * without removing it. * @return */ public long peek() { return stackArr[top]; } private void increaseStackCapacity(){ int[] newStack = new int[this.stackSize*2]; for(int i=0;i

 Output: ```Adding: 0 Adding: 1 Binary value of 2 is: 10 Adding: 1 Adding: 1 Adding: 1 Adding: 1 Binary value of 15 is: 1111 Adding: 1 Adding: 1 Adding: 1 Adding: 0 Adding: 1 Binary value of 23 is: 10111 ```