我正在做一个 karatsuba 实施,但我有这个错误:
java.lang.NumberFormatException: Zero length BigInteger
at java.math.BigInteger.<init>(BigInteger.java:296)
at java.math.BigInteger.<init>(BigInteger.java:476)
at com.Karatsuba.resolve(Karatsuba.java:20)
at com.Karatsuba.resolve(Karatsuba.java:26)
at com.KaratsubaTest.karatsubaShouldMultiply(KaratsubaTest.java:22)
这是我的方法:
BigInteger resolve(BigInteger left, BigInteger right) {
String leftS = left.toString();
String rightS = right.toString();
int digits = Math.max(leftS.length(), rightS.length());
digits = (digits / 2) + (digits % 2);
if (left.compareTo(new BigInteger("10", 10)) == -1 || right.compareTo(new BigInteger("10", 10)) == -1) {
return left.multiply(right);
}
BigInteger firstLeft = new BigInteger(leftS.substring(0, digits));
BigInteger secondLeft = new BigInteger(leftS.substring(firstLeft.toString().length(), leftS.length()));
BigInteger firstRight = new BigInteger(rightS.substring(0, digits));
BigInteger secondRight = new BigInteger(rightS.substring(firstRight.toString().length(), rightS.length()));
BigInteger z2 = resolve(firstLeft, firstRight);
BigInteger z0 = resolve(secondLeft, secondRight);
BigInteger z1 = resolve(firstLeft.add(secondLeft), firstRight.add(secondRight)).subtract(z2).subtract(z0);
return z2.multiply(BigInteger.valueOf((long) Math.pow(10, 2 * digits)))
.add(z1.multiply(BigInteger.valueOf((long) Math.pow(10, digits))))
.add(z0);
}
我认为这是因为我使用了不同的长度参数,例如 123 和 456789。知道吗?