[英]How to efficiently return the max possible integer with a given number of digits
For example, what would be the most efficient way to get say 999
if given an n
that equals 3 for instance. 例如,如果给出等于3的
n
,那么获得999
的最有效方法是什么。
This is what I have got right now but I was wondering if there was a more elegant way. 这就是我现在所拥有的,但我想知道是否有更优雅的方式。
public static int largestPossibleNumber(int numDigits) {
return Integer.parseInt(new String(new char[numDigits]).replace("\0", "9"));
}
Example Usage: 用法示例:
for (int i = 1; i <= 5; i++) {
System.out.println(largestPossibleNumber(i));
}
Output: 输出:
9
99
999
9999
99999
You have just 8 valid answers, so you can hardcode them: 您只有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];
}
You are asking for the most efficient way. 你问的是最有效的方法。 It's rather hard to prove that some way is the most efficient - it would require implementing and benchmarking multiple methods at least.
很难证明某种方式是最有效的 - 它至少需要实现和基准化多种方法。
But here's a pretty fast way to do this — just create a Map
, or use a switch
, see below. 但这是一个非常快速的方法 - 只需创建一个
Map
,或使用一个switch
,见下文。 This works because the size of an int
is fixed. 这是有效的,因为
int
的大小是固定的。 Note however, that this method won't extend to, say, BigInteger
s. 但请注意,此方法不会扩展到
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.