使用Stack将整数转换为二进制

时间:2014-04-10 11:46:54

标签: java binary stack

我是编程新手,但仍然急于解决这个问题。

我试图将一些剩余部分推入堆栈,然后弹出堆栈以二进制数字输出。

import java.util.Stack;

public class BinaryNumber {
    private static Stack<Integer> stack = new Stack<Integer>();
    private static int remainder;

public static String binaryNum(int number){
        while (number > 0){ //while number > 0
            if ((number % 2 != 1) && (number % 2 != 0)){ //if number is not equal to zero or 1
                number = (number-1); //update number to one less
                int remainder = 1;
            }
            else{
            int remainder = number % 2; //get the remainder
            }
            stack.push(new Integer(remainder));
            number /= 2;
        }
        stack.push(new Integer(1));
        return "hello".toString(); //just a test
    }
public static void printStack(){
    while (!stack.isEmpty()){
        stack.pop();
    }
}
    public static void main(String[]args){
        binaryNum(20);
        printStack();
    }
}

我似乎没有得到任何输出。我试图在纸面上解决问题并且无法弄清楚它在哪里失败。我之前确实有一些println语句,如果binaryNum中的语句总是被调用,它似乎是我的原始语句?

感谢。

2 个答案:

答案 0 :(得分:0)

您需要修改代码,如下所示: import java.util.Stack;

public class BinaryNumber {
    private static Stack<Integer> stack = new Stack<Integer>();
    private static int remainder;

public static String binaryNum(int number){
        while (number > 0){ //while number > 0
            if ((number % 2 != 1) && (number % 2 != 0)){ //if number is not equal to zero or 1
                number = (number-1); //update number to one less
                **remainder = 1;**
            }
            else{
                **remainder = number % 2; //get the remainder**
            }
            stack.push(new Integer(remainder));
            number /= 2;
        }
        stack.push(new Integer(1));
        return "hello".toString(); //just a test
    }
public static void printStack(){
    while (!stack.isEmpty()){
        **System.out.println(stack.pop());**
    }
}
    public static void main(String[]args){
        binaryNum(20);
        printStack();
    }
}

您正在做的是初始化两个局部变量'remaining'。添加到堆栈对象的是全局变量。

答案 1 :(得分:0)

你没有打印 - 这就是为什么没有输出!

试试这个(它确实有用):

import java.util.Stack;

public class BinaryNumber {
    private static Stack<Integer> stack = new Stack<Integer>();

    public static void binaryNum(int number) {
        // Important! In case you call binaryNum twice without calling printStack in between.
        stack.clear();
        while (number > 0) { // while number > 0
            int remainder = number % 2; // get the remainder
            stack.push(new Integer(remainder));
            number /= 2;
        }
    }

    public static void printStack() {
        while (!stack.isEmpty()) {
            System.out.print(stack.pop());
        }
    }

    public static void main(String[] args) {
        binaryNum(20);
        printStack();
    }
}