java - 如何在java中获得小数点位置的最大数字

标签 java

例如:

int getMax(int a) {
    return max;
}

a : 1 --> max : 9,
a : 2 --> max : 99,
a : 3 --> max : 999


等等。

谢谢。

最佳答案

对此有多种选择。鉴于您的方法只能返回 int,因此可用的选项并不多,因此您可以编写:

private static final int[] results = { 9, 99, 999, 9999, ... };

public static int getMax(int a) {
    // TODO: Validate argument
    return results[a - 1];
}

或者你可以循环:

public static int getMax(int a) {
    // TODO: Validate argument
    int result = 9;
    for (int i = 1; i < a; i++) {
        result = result * 10 + 9;
    }
}

或者您可以使用 Math.pow(),因为每个结果都是 10a - 1:

public static int getMax(int a) {
    // TODO: Validate argument
    return (int) (Math.pow(10, a) - 1);
}

关于java - 如何在java中获得小数点位置的最大数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28272711/

相关文章:

java - 如何用java生成日历?

Java future 异步?

java - 有没有办法将 "cut down"Java 对象传递给继承类?

java - 在java中对整数数组进行二进制搜索

java - 如何在 spring 中将所有请求映射到单个 Controller 方法?

java - 使用 Java 从 ArrayList 中删除所有空的 ArrayList

java - 如何使用 HttpURLConnection 在 Java Web 服务中执行身份验证

java - Selenium 网络驱动程序 : Automatically Repeating a successful scenario

java - 如何修复 JMeter 中的 java.io.NotSerializedException : org. apache.jmeter.JMeter$ListenToTest?

java - 如果整行以引号 "开头,Univocity CSV 解析器会粘合整行