LogicNewbie
LogicNewbie

Reputation: 65

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.

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

Upvotes: 3

Views: 862

Answers (4)

Alex Shesterov
Alex Shesterov

Reputation: 27525

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. This works because the size of an int is fixed. Note however, that this method won't extend to, say, BigIntegers.

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();
    }
}

Upvotes: 2

Dmitrii Bychenko
Dmitrii Bychenko

Reputation: 186668

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];
  }

Upvotes: 2

Kaidul
Kaidul

Reputation: 15875

public static int largestPossibleNumber(int numDigits) {
  return (int) (Math.pow(10, numDigits)) - 1;
}

Upvotes: 0

bucky
bucky

Reputation: 392

public static int largestPossibleNumber(int n) {
    return (int) (Math.pow(10.0, n)) -1;
}

Upvotes: 1

Related Questions