For example:
int getMax(int a) {
return max;
}
a : 1 --> max : 9,
a : 2 --> max : 99,
a : 3 --> max : 999
and so on.
Thanks.
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);
}
See more on this question at Stackoverflow