编写二进制代码的简单方法?

时间:2014-04-11 21:51:23

标签: java

需要一种在java中编写此方法而无需解析转换的方法。 (将数字转换为二进制) 这是一个简单的写作方式吗? " public static String toBinary(String num)"

给出十进制整数D:

1)将D除以2,将余数分开(记住,这些是整数)

2)总是在答案中插入任何先前二进制数字的LEFT,如果没有余数,则插入0,否则插入1。

3)重复步骤1& 2直到D为0

示例:

如果D = 49:

49/2 = 24余数1,所以在答案中插入1:1

24/2 = 12余数0,所以在答案中插入0:01

12/2 = 6余数0,所以在答案中插入0:001

6/2 = 3余数0,所以在答案中插入0:0001

3/2 = 1余数1,所以在答案中插入1:10001

1/2 = 0余数1,所以在答案中插入1:110001

D = 0,所以答案是110001

2 个答案:

答案 0 :(得分:1)

如果您已经拥有整数,那么您可以这样做:

Integer.toBinaryString(49)

将整数转换为二进制字符串。

答案 1 :(得分:0)

您列出的步骤本身就是代码。

    public static String toBinary(int number) {
        int remainder;
        String numString = "";

        while (number != 0) {

            //% operator is the modulo sign
            //this returns the remainder of (number / 2)
            remainder = number % 2;

            //divides in java always round down
            //so don't worry about the last number not being 0
            number = number / 2;

            //add the remainder to the leftmost side of the string.
            //notice how this means the Integer.toString comes first
            numString = Integer.toString(remainder) + numString;


            //if you can't use the Integer class 
            //use ("" + some_int) to let Java automatically convert
            //an integer some_int to a String for you e.g.:

            //numString = "" + remainder + numString;
        }

        return numString;
    }