如何编写一个 main 方法读取一个十进制数并打印其等效的二进制数?
写在3个班级 类 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
}
答案 0 :(得分:1)
您只需要将函数 Integer.toBinaryString() 与 System.out.println
结合并添加到 push 方法中:
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));
}