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

LogicNewbie :

For example, what would be the most efficient way to get say 999 if given an n that equals 3 for instance.

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
Dmitry Bychenko :

You have just 8 valid answers, so you can hardcode them:

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

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

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=92813&siteId=1