convert decimal to binary

落爺英雄遲暮 提交于 2021-01-29 19:47:56

问题


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"

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

回答1:


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



回答2:


You may directly print each binary digit without storing it in binaryNum

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

System.out.println();



回答3:


You can simply use Integer#toBinaryString(int) to return the result as a binary string.

        Scanner scan = new Scanner(System.in);

        int value = scan.nextInt();

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


来源:https://stackoverflow.com/questions/60552499/convert-decimal-to-binary

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!