I am doing the following exercise: The number of digits of a power of 2.. The statement is:
What is the number of digits of a power of 2?
2 ---> 1 digit 2 * 2 = 4 ---> 1 digit 2 * 2 * 2 = 8 ---> 1 digit 2 * 2 * 2 * 2 = 16 ---> 2 digits ... ... ... 2 * 2 * 2 * 2 * 2 * 2 * 2 * 2 * 2 * 2 = 1024 ---> 4 digits
Then, given the exponent, what would be the number of digits of that power?
I have tried the following answer:
import java.math.BigInteger;
public class Power {
public static long digit(long exp) {
System.out.println("exp: "+exp);
BigInteger pow = BigInteger.valueOf(2).pow((int)exp);
return String.valueOf(pow).split("").length;
}
}
However it times out with big exponents like: 562078812
How could we improve this solution? Is there any fastest answer?
I have also read:
The fastest answer is to use math.
The number of digits in 2^n is (nlog₁₀2)+1 .
You can achieve that by simply returning n * Math.log10(2) + 1
. Good luck.