将十进制转换为二进制

时间:2020-03-05 19:13:04

标签: java binary

代码大部分已完成,但是我的代码未正确打印,其打印输出为110,而不是011。我正在做的问题需要将“ 110”反转为“ 011”

bintest(isMemberR)

3 个答案:

答案 0 :(得分:1)

然后使用如下字符串:

   int num = scan.nextInt();

   String s = "";
   while (num != 0) {
    int   rem = num % 2;
      num /= 2;
      s = s + rem; // this concatenates the digit to the string in reverse order.

      // if you want it in normal order, do it ->  s = rem + s;
   }
   System.out.println(s);

答案 1 :(得分:0)

您可以简单地使用Integer#toBinaryString(int)将结果作为二进制字符串返回。

        Scanner scan = new Scanner(System.in);

        int value = scan.nextInt();

        System.out.println(Integer.toBinaryString(value));

答案 2 :(得分:0)

您可以直接打印每个二进制数字,而无需将其存储在binaryNum

while (num != 0) {
    System.out.print(num % 2);
    num /= 2;
}

System.out.println();