簡體   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