java - 十进制转二进制,打印错误答案

标签 java binary stack decimal

嘿,我想知道是否有人能发现我的代码有问题吗?如果可以的话,请给我解释一下!当我输入 99 时,我得到 1100 011,而它应该是 0110 0011。

import java.util.*;
public class SchoolHomework {

/**
 * @param args the command line arguments
 */
public static void main(String[] args) {
    System.out.println("Program that converts decimal to binary!");
    int dec;
    System.out.println("Please type in a decimal number:");
    Scanner input = new Scanner(System.in);
    Stack<Integer> todec = new Stack<Integer>();
    dec = input.nextInt();
    if (dec < 0){
        System.out.println("Error: Please enter a positive number!");
        System.exit(0);
    }
    while (dec != 0){
        int stackv = dec % 2;
        todec.push(stackv);
        dec /= 2;

    }
    System.out.println(dec + " To binary is: ");
    int counter = 0;
    while (!(todec.isEmpty() )) {
        String val = todec.pop().toString();
        System.out.print(val);
        counter = counter + 1;
        if (counter >= 4){
            counter = 0;
            System.out.print(" ");
        }

    }
}
}

最佳答案

你写的算法看起来很不错。你离解决方案很近了。最简单的方法是继续将零压入堆栈,直到长度达到 4 的倍数。如果你有什么好意见,请告诉我 ;)

import java.util.*;
public class SchoolHomework {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        System.out.println("Program that converts decimal to binary!");
        int dec;
        System.out.println("Please type in a decimal number:");
        Scanner input = new Scanner(System.in);
        Stack<Integer> todec = new Stack<Integer>();
        dec = input.nextInt();
        if (dec < 0){
            System.out.println("Error: Please enter a positive number!");
            System.exit(0);
        }
        int size = 0;

        while (dec != 0){
            int stackv = dec % 2;
            todec.push(stackv);
            dec /= 2;
            size++;
        }
        if (size % 4 > 0) {
            for(int i = 0; i < 4 - (size % 4); i++) {
               todec.push(0);
            }
        }
        System.out.println(dec + " To binary is: ");
        int counter = 0;
        while (!(todec.isEmpty() )) {
            String val = todec.pop().toString();
            System.out.print(val);
            counter = counter + 1;
            if (counter >= 4){
                counter = 0;
                System.out.print(" ");
            }

        }
    }
}

关于java - 十进制转二进制,打印错误答案,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35308963/

相关文章:

java - 房间数据库查询

java - 挑战 : Custom Animation of ViewPager. 更改所选元素的高度(View fold)

java - 如何使用 getWidth() 获取 View 的宽度?

c - *((int*)&f) 在 C 中做什么?

c++ - 如何将一个非常大的二进制数转换为十进制数?

在 C 中创建一个 FIFO 队列

c# - 使用默认值初始化队列或堆栈?

java - 限制 Hibernate 自定义 FileMaker 方言中的结果

binary - 十进制数 104 的二进制等价物

javascript - 如何通过 JavaScript 中的回调避免堆栈蠕变?