1

how write a main method read a decimal number and print its equivalent binary number ?

write in 3 class class 1:Node 2: stackPtr 3: stackPtrMain

ineed to print binary number using ( s.push )

I want an example

In the output

(s.push(17);) The decimal number 17 in binary is 10001

( s.push(20); ) The decimal number 20 in binary is 10100

( s.push(23); ) The decimal number 23 in binary is 101111

( s.push(26); ) The decimal number 26 in binary is 11010

BUILD SUCCESSFUL (total time: 0 seconds)

import java.util.*;
class Node
{
    int data;
    Node next;   // by default it refers to null
    Node (int d) {data = d;  }   //constructor of the Node class
}
class stackPtr
{
    private Node top;
    
public void push(int x)
{
    Node N = new Node(x);   // create a new node with data x
    N.next = top;           // new node refer to the stack top
    top = N;                // the new node will be the stack top
}

public boolean isEmpty(){ return top == null;}   // the stack is empty when top == null 

public int Top ()
   { if (!isEmpty()) return top.data;  else return -11111; }


public void pop()
{
  if (!isEmpty()) top = top.next;  else System.out.println("Stack is Empty"); 
}

void makeNull(){top = null; }
}
class stackPtrMain
{

public static void main(String arg[])
 {
stackPtr s = new stackPtr() ;
s.push(17);
s.push(20);
s.push(23);
s.push(26);
while(!s.isEmpty())
  { System.out.println(s.Top());
    s.pop();
  }
}// End of the main function
}
dreamcrash
  • 47,137
  • 25
  • 94
  • 117
juman jl
  • 35
  • 4

1 Answers1

1

You just need to combine the function Integer.toBinaryString() with System.out.println and added to the push method:

public void push(int x)
{
    Node N = new Node(x);   // create a new node with data x
    N.next = top;           // new node refer to the stack top
    top = N;                // the new node will be the stack top
    System.out.println("The decimal number "+x+" in binary is "+Integer.toBinaryString(x));
}
dreamcrash
  • 47,137
  • 25
  • 94
  • 117