Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I examine each digit of a BigInteger in Java?

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?

like image 900
djscribbles Avatar asked Oct 16 '12 18:10

djscribbles


3 Answers

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);
}
like image 148
Victor Sorokin Avatar answered Sep 27 '22 23:09

Victor Sorokin


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.

like image 26
maerics Avatar answered Sep 27 '22 23:09

maerics


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.

like image 35
A.H. Avatar answered Sep 27 '22 23:09

A.H.