Java十进制数换算二进制数(栈实现)

2014-12-08 06:30:01 阅读( 129 )

2755人 收藏本页

标签:Java面试题

import java.io.*;
public class textBoard {
public Node head = null;

public static void main(String[] args){
String s = “”;
int num = 0;
textBoard board = new textBoard();
System.out.print(“Please input a Decimal number : “);
//Input function!
try {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
s = in.readLine();
num = Integer.parseInt(s);
}catch(IOException e) {}
System.out.println(“Your entering Binary number is: ” + board.swap(num));
}

public String swap(int i){
while(i != 1) {
Node node = new Node(i % 2);
push(node);
i = i / 2;
}
Node node1 = new Node(1);
push(node1);
String s = “”;
while(!isEmpty()){
s += head.getkey();
head = head.getnext();
}
return s;
}

public void push(Node element){
if(element != null){
element.setnext(head);
head = element;
}
}

public boolean isEmpty(){
if(head == null){
return true;
}
return false;
}
}
class Node {
private int key = 0;
private Node next = null;

public Node(int i) {
this.key = i;
this.next = null;
}

public int getkey(){
return key;
}

public void setkey(int i){
this.key = i;
}

public Node getnext(){
return next;
}

public void setnext(Node next){
this.next = next;
}
}

来自IT公司面试手册

下一篇:Java代码计算三角形的周长和面积

上一篇:java程序员应该掌握的10项技能

亲~ 如果您有更好的答案 可在评论区发表您独到的见解。

您想查看更多的信息: 面试题