Java - Round number up so number of digits increments

≡放荡痞女 提交于 2020-01-15 11:26:36

问题


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!)


回答1:


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)));
}



回答2:


Try

double input = ...
double output = Math.pow(10, Math.ceil(Math.log10(input)));

You can cast your output to an integer then. The operations amount is constant so O(1) is guaranteed for a single input.



来源:https://stackoverflow.com/questions/26266195/java-round-number-up-so-number-of-digits-increments

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!