【问题标题】:read decimal number and print its equivalent binary number [duplicate]读取十进制数并打印其等效的二进制数[重复]
【发布时间】:2021-06-13 20:54:38
【问题描述】:

如何编写一个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
}

【问题讨论】:

    标签: java stack


    【解决方案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));
    }
    

    【讨论】:

      猜你喜欢
      • 2020-05-09
      • 2014-04-24
      • 1970-01-01
      • 2016-12-13
      • 2022-11-29
      • 2011-12-27
      • 1970-01-01
      • 2018-06-09
      • 1970-01-01
      相关资源
      最近更新 更多