例如,如果给定一个等于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
{0, 9, 99, 999, ..., 99999999 }
,然后通过索引获取该值。 - Dmitry Bychenkoprivate static int[] data = {0, 9, 99, 999, 9999, 99999, 999999, 9999999, 99999999};
进行硬编码。 - Dmitry Bychenko"999999999".substring(0, numberOfDigits)
。是的,我知道它返回一个字符串而不是一个int
。如果你需要将其解析为int
,它可能不再是运行时高效的,但仍然很容易阅读,所以是否需要取决于你对“高效”的理解。 - Ole V.V.