[英]convert decimal to binary
代碼大部分都完成了,但我的代碼打印不正確,它的打印結果是 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);
}
}
然后使用如下字符串:
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);
您可以簡單地使用 Integer#toBinaryString(int) 將結果作為二進制字符串返回。
Scanner scan = new Scanner(System.in);
int value = scan.nextInt();
System.out.println(Integer.toBinaryString(value));
您可以直接打印每個二進制數字,而無需將其存儲在binaryNum
while (num != 0) {
System.out.print(num % 2);
num /= 2;
}
System.out.println();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.