public class Test {
public static void main(String[] args) throws IOException {
Scanner scanner = new Scanner(System.in);
System.out.println("请输入0到511之间的一个整数:");
int num = scanner.nextInt();
while (num < 0 || num > 511) {
System.out.println("输入的数字不在[0,511]的范围,请重新输入");
num = scanner.nextInt();
}
// 直接用自带的转二进制的方法,然后将0替换成H
String binaryString = Integer.toBinaryString(num); //
binaryString = binaryString.replaceAll("0", "H");
System.out.println(binaryString);
// 自己写算法计算并用H代替0
String binary = "";
while (num > 0) {
int i = num % 2;
if (i == 0) {
binary = "H" + binary;
} else {
binary = "1" + binary;
}
num = num / 2;
}
System.out.println(binary);
}
}