妈妈再也不用担心十进制数过大了233
import com.google.common.base.Strings;
import java.math.BigInteger;
import java.util.Scanner;
/**
* 任意长度十进制数转化为二进制
*/
public class AnyNumberConverterFromDecimalToBinary {
/**
*
* @param srcNum 待转换的十进制数
* @return 二进制字符串
*/
private static String convertFromDecimalToBinary(String srcNum){
BigInteger src = new BigInteger(srcNum);
StringBuilder sb = new StringBuilder();
BigInteger zero = new BigInteger("0");
BigInteger two = new BigInteger("2");
while (!zero.equals(src)) {
sb.append(src.remainder(two));
src = src.divide(two);
}
return sb.reverse().toString();
}
/**
* 格式检查
* @param srcNum
* @return 若可以转化为整数, 返回true; 否则返回false
*/
private static boolean FormatCheck(String srcNum){
if (Strings.isNullOrEmpty(srcNum)){
return false;
}
if (!isDigit(srcNum)) {
return false;
}
return true;
}
/**
* 判断一个字符串中每个字符是否都为数字
* @param strNum
* @return 若每个字符都是数字, 返回true; 否则返回 false
*/
private static boolean isDigit(String strNum) {
return strNum.matches("[0-9]{1,}");
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String srcNum = sc.nextLine();
if (!FormatCheck(srcNum)) {
System.out.println("格式错误");
return ;
}
System.out.println(convertFromDecimalToBinary(srcNum));
}
}