读取十进制数并打印其等效的二进制数

read decimal number and print its equivalent binary number

如何编写 main 方法读取十进制数并打印其等效的二进制数?

写3 class class 1:节点 2: stackPtr 3: stackPtrMain

需要使用 ( s.push )

打印二进制数

我要一个例子

在输出中

(s.push(17);) 十进制数17用二进制表示是10001

( s.push(20); ) 十进制数20用二进制表示是10100

( s.push(23); ) 十进制数23用二进制表示是101111

( s.push(26); ) 十进制数26用二进制表示是11010

构建成功(总时间:0 秒)

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
}

你只需要将函数Integer.toBinaryString()System.out.println组合起来并添加到推送方法中:

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));
}