繁体   English   中英

如何有效地返回给定位数的最大可能整数

[英]How to efficiently return the max possible integer with a given number of digits

例如,如果给出等于3的n ,那么获得999的最有效方法是什么。

这就是我现在所拥有的,但我想知道是否有更优雅的方式。

public static int largestPossibleNumber(int numDigits) {
  return Integer.parseInt(new String(new char[numDigits]).replace("\0", "9"));
}

用法示例:

for (int i = 1; i <= 5; i++) {
  System.out.println(largestPossibleNumber(i));
}

输出:

9
99
999
9999
99999

您只有8个有效答案,因此您可以对它们进行硬编码

  private static int[] s_Numbers = {
    0, 9, 99, 999, 9999, 99999, 999999, 9999999, 99999999};

  private static int largestPossibleNumber(int n) {
    return s_Numbers[n];
  }

你问的是最有效的方法。 很难证明某种方式是有效的 - 它至少需要实现和基准化多种方法。

但这是一个非常快速的方法 - 只需创建一个Map ,或使用一个switch ,见下文。 这是有效的,因为int的大小是固定的。 但请注意,此方法不会扩展到BigInteger

public static int largestPossibleNumber(final int numDigits) {
    switch (numDigits) {
        case 1: return 9;
        case 2: return 99;
        case 3: return 999;
        case 4: return 9999;
        case 5: return 99999;
        case 6: return 999999;
        case 7: return 9999999;
        case 8: return 99999999;
        case 9: return 999999999;
        case 10: return Integer.MAX_VALUE;
        default: throw new IllegalArgumentException();
    }
}
public static int largestPossibleNumber(int n) {
    return (int) (Math.pow(10.0, n)) -1;
}
public static int largestPossibleNumber(int numDigits) {
  return (int) (Math.pow(10, numDigits)) - 1;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM