Janghyun Yim
Janghyun Yim

Reputation: 11

How to make a maxium number of the position of the decimal point, in java

For example:

int getMax(int a) {
    return max;
}

a : 1 --> max : 9,
a : 2 --> max : 99,
a : 3 --> max : 999


and so on.

Thanks.

Upvotes: 1

Views: 69

Answers (1)

Jon Skeet
Jon Skeet

Reputation: 1500225

There are various options for this. Given that your method can only return int, there aren't very many options available, so you could just write:

private static final int[] results = { 9, 99, 999, 9999, ... };

public static int getMax(int a) {
    // TODO: Validate argument
    return results[a - 1];
}

Or you could loop:

public static int getMax(int a) {
    // TODO: Validate argument
    int result = 9;
    for (int i = 1; i < a; i++) {
        result = result * 10 + 9;
    }
}

Or you could use Math.pow(), given that each result is 10a - 1:

public static int getMax(int a) {
    // TODO: Validate argument
    return (int) (Math.pow(10, a) - 1);
}

Upvotes: 2

Related Questions