问题
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