/*
Enter a decimal number: 5
0B101
Enter a decimal number: 45
0B101101
*/
import java.util.Scanner;
public class DecimalToBinary {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter a decimal number: ");
int d = input.nextInt();
String s = decimalToBinary(d);
System.out.println("0B" + s); //编程语言中以“0B”开头的表示二进制数
}
public static String decimalToBinary(int d) {
char[] ch = new char[1];
StringBuilder stringBuilder = new StringBuilder();
/* ch[0] = (char)(d % 2)输出结果为空白,Java不允许int类型
* 直接转换为char字符。
*/
do {
ch[0] = (char) ('0' + d % 2);
stringBuilder.append(ch);
} while ((d /= 2) != 0);
stringBuilder.reverse();
return stringBuilder.toString();
}
}
Introduction to Java Programming编程题9.10<十进制转二进制>
最新推荐文章于 2015-09-28 19:58:09 发布