十进制转二进制(包括负数)
import java.util.Scanner;
public class BinaryConverter {
private final String TABLE = "01";
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
BinaryConverter bc = new BinaryConverter();
System.out.println("请输入十进制数:");
int num = scanner.nextInt();
String binary = bc.binaryConverter(num);
System.out.println(binary);
scanner.close();
}
/**
* 判断符号
* @param num
* @return
*/
private int sign(int num) {
if (num > 0) {
return 1;
}else if (num == 0) {
return 0;
}else {
return -1;
}
}
/**
* 十进制转二进制
* @param num
*/
public String binaryConverter(int num) {
if (sign(num) == 0) {
return String.valueOf(num);
}
if (sign(num) == 1) {
String result= "";
while (num != 0) {
int a = num % 2;
char ch = TABLE.charAt(a);
re