简体   繁体   English

十进制转二进制

[英]convert decimal to binary

Code is mostly done but my code is printing incorrectly its printing out as 110 as opposed to 011. The problem im doing requires to reverse the "110" to "011"代码大部分都完成了,但我的代码打印不正确,它的打印结果是 110 而不是 011。我做的问题需要将“110”反转为“011”

import java.util.Scanner; 

public class LabProgram {   
    public static void main(String[] args) { 

Scanner scan = new Scanner(System.in);


   int num, binaryNum = 0;
   int i = 1, rem;

   num = scan.nextInt();

   while (num != 0)
   {
      rem = num % 2;
      num /= 2;
      binaryNum += rem * i;
      i *= 10;
   }


 System.out.println(binaryNum);
}
}

Then use a string as follows:然后使用如下字符串:

   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);

You can simply use Integer#toBinaryString(int) to return the result as a binary string.您可以简单地使用 Integer#toBinaryString(int) 将结果作为二进制字符串返回。

        Scanner scan = new Scanner(System.in);

        int value = scan.nextInt();

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

You may directly print each binary digit without storing it in binaryNum您可以直接打印每个二进制数字,而无需将其存储在binaryNum

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

System.out.println();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM