How can I examine each digit (System.out.println()
each digit, for instance) of a BigInteger in Java? Is there any other way other than converting it to a string?
Straight-forward code prints digits from the last towards the first:
private static void printDigits(BigInteger num) {
BigInteger[] resultAndRemainder;
do {
resultAndRemainder = num.divideAndRemainder(BigInteger.TEN);
System.out.println(Math.abs(resultAndRemainder[1].intValue()));
num = resultAndRemainder[0];
} while (num.compareTo(BigInteger.ZERO) != 0);
}
The BigInteger
API docs do not appear to provide any functionality as such. Moreover, the numbers are quite likely not represented in base 10 (since it would be quite inefficient). So it is most likely that the only way to inspect the decimal digits of a BigInteger is to look at its string representation.
You could of course use basic math to calculate each digit. Especially the method divideAndRemainder
might help here. But I doubt, that this is more efficient than converting to a String and examing the characters. BigInteger
math is more expensive than plain int
or long
math after all.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With