Here's a quick method based on the Dariusz answer :
public static int getDigitCount(BigInteger number) { double factor = Math.log(2) / Math.log(10); int digitCount = (int) (factor * number.bitLength() + 1); if (BigInteger.TEN.pow(digitCount - 1).compareTo(number) > 0) { return digitCount - 1; } return digitCount; }
The following code checks the numbers 1, 9, 10, 99, 100, 999, 1000, etc. up to ten thousand digits:
public static void test() { for (int i = 0; i < 10000; i++) { BigInteger n = BigInteger.TEN.pow(i); if (getDigitCount(n.subtract(BigInteger.ONE)) != i || getDigitCount(n) != i + 1) { System.out.println("Failure: " + i); } } System.out.println("Done"); }
This can check BigInteger with 184,948 decimal digits and more for a second.
dln385
source share