System.out.print("Enter an integer: ");
int number = input.nextInt();
String binary = "";
while(number != 0) {
if (number % 2 == 0) {
binary += "0" ;
} else{
binary += "1" ;
}
number /= 2;
}
System.out.println(binary);
我无法理解我的代码有什么问题。
我看到有这个问题的解决方案,但他们没有回答我的以下问题:
我知道要以正确的方式显示二进制文件,我需要更改这一行:binary += "0";
到此行:binary = "0" + binary;
我无法理解为什么,为什么当我编写该代码时,输出不应该反转,但如果我添加行,则会以正确的方式打印。
感谢。
答案 0 :(得分:3)
你的代码一直在检查2的模数,这实际上是数字的最低有效位,然后它除以2以继续下一位(向右移动一位)。例如:
29 = 11101
^ check modulo of two,
append "1",
divide by two
14 = 1110
^ check modulo of two,
append "0",
divide by two
7 = 111
^ check modulo of two,
append "1",
divide by two
3 = 11
^ check modulo of two,
append "1",
divide by two
1 = 1
^ check modulo of two,
append "1",
divide by two
(stop)
如您所见,算法按顺序追加:
实际上这与二进制表示相反。因此,换句话说,您需要在String
:
while(number != 0) {
if (number % 2 == 0) {
binary = "0" + binary;
} else {
binary = "1" + binary;
}
number /= 2;
}
答案 1 :(得分:1)
您要按相反的顺序追加二进制数字。
您附加到String
的第一个数字成为String
的第一个数字,这意味着最低有效位成为输出String
中最重要的位。
应该是:
String binary = "";
while (number != 0) {
if (number % 2 == 0) {
binary = "0" + binary; // the newly appended digit should be to the left of the
// previously appended digits
} else {
binary = "1" + binary;
}
number /= 2;
}
System.out.println(binary);
举一个简单的例子:
让number == 2
第一次迭代:
number % 2 == 0
binary = "0" + binary; // "0" + "" -> "0"
number /= 2; // now number == 1
第二次迭代:
number % 2 != 0
binary = "1" + binary; // "1" + "0" -> "10"
number /= 2; // now number == 0
答案 2 :(得分:1)
String t1 = driver.findElement(By.xpath("/html/body/font/strong/em")).getText();
System.out.println(t1);
您可以在二进制字符串的前面添加。
使用reverse()方法还有另一种方法。
String binary = "";
while (number != 0) {
if (number % 2 == 0) {
binary = "0" + binary;
} else {
binary = "1" + binary;
}
number /= 2;
}
System.out.println(binary);