In: Computer Science
You may not use the java.util.Stack
class.
You may not use the java.util.Queue class.
Ex1: Write a program that converts a decimal to
binary using a stack.
My professor gave me this question to code, is this even possible? if it is can someone code it, in java.
We can implement the stack using arrays.
Code:
import java.util.*;
public class Main
{
static int stack[]=new int[100];
static int top=-1;
/*Implementation of push */
public static void push(int b)
{
top=top+1;
stack[top]=b;
}
/*Implementation of pop */
public static int pop()
{
int b=stack[top];
top=top-1;
return (b);
}
public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);
System.out.print("Enter decimal number::");
int n=sc.nextInt();
int r;
/*If decimal number is 0 the directly push 0*/
if(n==0)
{
push(0);
}
else
{
while(n>0)
{
r=n%2;
push(r);
n=n/2;
}
}
System.out.print("The binary number is::");
while(top>=0)
{
System.out.print(pop());
}
}
}
Screenshots: