I have a collection of BigInteger
s and am trying to get the number of digits in each integral number. For the sake of brevity, lets say that we are only dealing with positive numbers. We are looking at numbers with over 1000 digits.
The following are the ways I have thought of.
length of a string representation (will require a bunch of memory)
modulo 10 approach (slow)
an asanine idea (included for sake of thoroughness, since scalability of this approach is not great)
if (i >= 100000000) { i /= 100000000; n += 8; } if (i >= 10000) { i /= 10000; n += 4; } if (i >= 100) { i /= 100; n += 2; } if (i >= 10) { i /= 10; n += 1; }
logarithms (which I find rather friendly) (credits go to [this answer])
int blex = val.bitLength() - 1022; // any value in 60..1023 is ok if (blex > 0) val = val.shiftRight(blex); double res = Math.log10(val.doubleValue()); return blex > 0 ? res + blex * LOG2 : res;
This is an idea I have but want to test the validity of before coding; say I have some number
x
. Try to divide by powers of 10 using concepts of (traditional or one-sided) binary search, and stop when0 < quotient < 10
. Thatpower + 1
should be the number of digits. This would be a logarithmic solution (?).
StackOverflow did not really seem to have something solid to calculate the number of digits in any number. This accepted answer suggests a division-heavy approach that can result in a bunch of new objects being created. I was wondering if there can be a slicker solution. So, I thought this post would lead to a fruitful discussion and collaboration of ideas. Please suggest which method would work best for really large numbers.