What is the most efficient way (in Java) to round a number n up to the nearest power of ten which contains one more digit than the original number?
e.g. 3 -> 10
432 -> 1,000
241,345 -> 1,000,000
Is there a way to get it in a single O(1) line?
A simple way I can see is to use a for loop and increment the power of ten until n / (10 ^ i) < 1, but then that isn't O(1) and is O(log n) instead. (well I'm taking a guess it's log n as it involves a power!)
If you're looking for a string, you can use Math.log10
to find the right index into an array:
// Do more of these in reality, of course...
private static final String[] MESSAGES = { "1", "10", "100", "1,000", "10,000" };
public static final String roundUpToPowerOf10(int x) {
return MESSAGES[(int) Math.ceil(Math.log10(x))];
}
If you want it to return the integer with the right value, you can use use Math.pow
:
public static final int roundUpToPowerOf10(int x) {
return (int) Math.pow(10, Math.ceil(Math.log10(x)));
}
See more on this question at Stackoverflow