Java convert a decimal number to binary using stack

Examples

package com.w3spoint;
 
public class Test {
    private int stackSize;
    private int[] stackArray;
    private int top;
 
    /**
     * constructor to create stack with size
     * @param size
     */
    public Test(int size) {
        this.stackSize = size;
        this.stackArray = new int[stackSize];
        this.top = -1;
    }
 
    /**
     * Adds new entry to the top of the stack
     * @param entry
     * @throws Exception 
     */
    public void push(int entry) throws Exception {
    	this.stackArray[++top] = entry;
    }
 
    /**
     * Removes an entry from the top of the stack.
     * @return
     * @throws Exception 
     */
    public int pop() throws Exception {
        if(this.isStackEmpty()){
        	System.out.println("Stack underflow.");
        }
        return this.stackArray[top--];
    }
 
    /**
     * Returns top of the stack without removing it.
     * @return
     */
    public int peek() {
        return stackArray[top];
    }
 
    /**
     * Returns true if the stack is empty
     * @return
     */
    public boolean isStackEmpty() {
        return (top == -1);
    }
 
    /**
     * Returns true if the stack is full
     * @return
     */
    public boolean isStackFull() {
        return (top == stackSize - 1);
    }
 
    public String convertDecialToBinary(int number) throws Exception{        
        StringBuilder binary = new StringBuilder();
        if(number == 0){
            binary.append("0");
        } else {
            while(number != 0){
                push(number%2);
                number = number/2;
            }
        }
        while(!isStackEmpty()){
            try {
                binary.append(pop());
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return binary.toString();
    }
 
	public static void main(String args[]){
		try {
			Test test = new Test(10);
			int number = 15;
			System.out.println("Original number: " + number);
			System.out.println("Binary number: " + test.convertDecialToBinary(number));
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}

Output

Original number: 15
Binary number: 1111
Please follow and like us:
Content Protection by DMCA.com