【发布时间】:2015-09-30 06:00:19
【问题描述】:
抱歉,可能有重复的帖子,我在这里看到了许多类似的主题,但没有一个是我真正需要的。在实际发布问题之前,我想明确声明这个问题不是家庭作业。
那么问题来了:如何将一个大整数转换成二进制表示?整数足够大以适合原始类型(Java long 不能使用)。输入可以表示为字符串格式或数字数组。免责声明,这不会是生产级别的解决方案,所以我不想使用 BigInteger 类。相反,我想实现一个算法。
到目前为止,我最终采用了以下方法: 以字符串表示的输入和输出值。如果输入的最后一位是偶数,我在输出前加上“0”,否则 - 加上“1”。之后,我将输入替换为输入除以 2。我使用另一种方法 - divideByTwo 进行算术除法。此过程循环运行,直到输入变为“0”或“1”。最后,我将输入添加到输出中。代码如下:
辅助方法
/**
* @param s input integer value in string representation
* @return the input divided by 2 in string representation
**/
static String divideByTwo(String s)
{
String result = "";
int dividend = 0;
int quotent = 0;
boolean dividendIsZero = false;
while (s.length() > 0)
{
int i = 1;
dividend = Character.getNumericValue(s.charAt(0));
while (dividend < 2 && i < s.length())
{
if (dividendIsZero) {result += "0";}
dividend = Integer.parseInt(s.substring(0, ++i));
}
quotent = dividend / 2;
dividend -= quotent * 2;
dividendIsZero = (dividend == 0);
result += Integer.toString(quotent);
s = s.substring(i);
if (!dividendIsZero && s.length() != 0)
{
s = Integer.toString(dividend) + s;
}
}
return result;
}
主要方法
/**
* @param s the integer in string representation
* @return the binary integer in string representation
**/
static String integerToBinary(String s)
{
if (!s.matches("[0-9]+"))
{
throw new IllegalArgumentException(s + " cannot be converted to integer");
}
String result = "";
while (!s.equals("0") && !s.equals("1"))
{
int lastDigit = Character.getNumericValue(s.charAt(s.length()-1));
result = lastDigit % 2 + result; //if last digit is even prepend 0, otherwise 1
s = divideByTwo(s);
}
return (s + result).replaceAll("^0*", "");
}
如您所见,运行时间为 O(n^2)。 integerToBinary 方法的 O(n) 和循环内运行的 divideByTwo 的 O(n)。有没有办法实现更好的运行时?提前致谢!
【问题讨论】:
标签: java algorithm binary integer largenumber