有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java将十进制转换为二进制

代码大部分都完成了,但我的代码打印不正确,打印出来的是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);
}
}

共 (3) 个答案

  1. # 1 楼答案

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

    while (num != 0) {
        System.out.print(num % 2);
        num /= 2;
    }
    
    System.out.println();
    
  2. # 2 楼答案

    然后使用如下字符串:

       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);
    
  3. # 3 楼答案

    您可以简单地使用Integer#tobinarysting(int)以二进制字符串的形式返回结果

            Scanner scan = new Scanner(System.in);
    
            int value = scan.nextInt();
    
            System.out.println(Integer.toBinaryString(value));