Java - 向上舍入,使位数递增 [英] Java - Round number up so number of digits increments

查看:53
本文介绍了Java - 向上舍入,使位数递增的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

将数字 n 舍入到比原始数字多一位的最接近的十的幂的最有效方法是什么(在 Java 中)?

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?

例如3 -> 10

432 -> 1,000

432 -> 1,000

241,345 -> 1,000,000

241,345 -> 1,000,000

有没有办法在单个 O(1) 行中得到它?

Is there a way to get it in a single O(1) line?

我能看到的一个简单方法是使用 for 循环并增加 10 的幂直到 n/(10 ^ i) <1,但那不是 O(1) 而是 O(log n) .(好吧,我猜它是 log n,因为它涉及到一个权力!)

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

推荐答案

如果您要查找字符串,可以使用 Math.log10 以找到数组中的正确索引:

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

如果你想让它返回具有正确值的整数,你可以使用 Math.pow:

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

这篇关于Java - 向上舍入,使位数递增的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆