Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

A stack can be used to convert decimal numbers to binary numbers. You are to wri

ID: 3831233 • Letter: A

Question

A stack can be used to convert decimal numbers to binary numbers. You are to write the method displayBinary that will convert a decimal number into a binary a number using stack. The pseudocode for an algorithm that converts a decimal number to a binary number is given below. public static void displayBinary (int decimalNum)(Stack stck=new Stack () while decimalNum not equal to 0(find remainder when decimalNum is divided by 2 push remainder on the stack divide the decimalNum by 2 while stack isn't empty pop num off the stack and display Use the following header in writing your method displayBinary. Display the binary representation of decimalNum. Precondition: decimalNum>0 public static void displayBinary (int decimalNum)

Explanation / Answer

import java.util.*;

/* DecimalToBinaryUsingStacks */
public class DecimalToBinaryUsingStacks
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
/* Creating Stack object */
Stack<Integer> stk = new Stack<Integer>();
/* 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(" Binary 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

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote