我有一个将小数转换为二进制的代码,但是在测试时,我注意到如果输入八进制,则会输出“错误的”结果。
我想知道是否有任何方法可以在调用函数时将八进制输入为整数输入时排除八进制。因此,如果将0123用作参数而不是123,则该方法将使用123作为输入运行,或者对于无效输入返回null。 该方法必须以int作为输入。
wrapper方法检查十进制数是否小于0,并且帮助程序以递归方式找到二进制字符串。最后,包装器删除前导0并输出一个二进制字符串。
public static String decimalToBinary(int decimal) {
if (decimal < 0) {
return null;
}
String result = xDecimalToBinary(decimal);
/*
* the following section checks for a string of 0s and removes all of them,
* leaving the last one if the string is all 0s
*/
if (result.charAt(0) == '0') {
result.replaceFirst("^0+(?!$)", "");
}
return "0b" + result;
}
private static String xDecimalToBinary(int decimal) {
if (decimal == 0 || decimal == 1) {
return "" + decimal;
}
/*
* builds binary string right to left taking the recursion of decimalToBin of
* decimal / 2 on the left and the remainder of decimal / 2 (%2) on the right
*/
else {
return "" + xDecimalToBinary(decimal / 2) + decimal % 2;
}
}
注意:这是针对一堂课的,但是此特定功能不是作业的一部分,而是出于我的好奇心。
答案 0 :(得分:0)
你不能。
0123是用Java编写数字“八十三”的一种方法。
如果要“ 123”,则必须写123(或0173或0x7b)。
您正在告诉您的方法将八十三转换为二进制,并且这样做。您的方法没有问题。