Wednesday, 29 November 2017

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


Code:

import java.util.*;

/*  DecimalToBinaryUsingStacks  */
public class DecimalToBinaryUsingStacks
{
    public static void main(String[] args) 
    {    
        Scanner scan = new Scanner(System.in);
        /* Creating Stack object  */
        Stack stk = new Stack();
        /* Accepting number */        
        System.out.println("Enter decimal number");
        int num = scan.nextInt();

        while (num != 0)
        {
            int d = num % 2;
            stk.push(d);
            num /= 2;
        }        
        /* Print Binary equivalent */
        System.out.print("\nBinary equivalent = ");
        while (!(stk.isEmpty() ))
        {
            System.out.print(stk.pop());
        }
        System.out.println();
    }
}


Output:

Enter decimal number
12345

Binary equivalent = 11000000111001


Enter decimal number
99

Binary equivalent = 1100011


Enter decimal number
24162

Binary equivalent = 101111001100010


Enter decimal number
347562318

Binary equivalent = 10100101101110110000101001110


More Java Programs:



















100+ Best Home Decoration Ideas For Christmas Day 2019 To Make Home Beautiful

Best gifts for Christmas Day | Greeting cards for Christmas Day | Gift your children a new gift on Christmas day This Christmas d...