Finding largest number in Java

I am trying to find the large number in java by using the integer parameter. I converted the integer value to string but the problem is, it failed on the run and did not show the expected result.

Here is the case:

Given an integer n, it returns the largest number that contains exactly n digits only when n is non-zero.

  • For n = 1, the output should be largestNumber(n) = “9”.
  • For n = 2, the output should be largestNumber(n) = “99”.
  • For n = 3, the output should be largestNumber(n) = “999”.
  • For n =0, the output should be largestNumber(n) = “-1”.

Constraints 0 ≤ |n| ≤ 10

Here is the java code :

class Result {
  /*
   * Complete the 'largestNumber' function below.
   *
   * The function is expected to return a STRING.
   * The function accepts INTEGER n as parameter.
   */
public static String largestNumber(int n) { // Write your code here
String res = Integer.toString(n);
return res;
}
                   
}public static void main(String[] args) throws IOException {
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in)); BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(System.getenv("OUTPUT_PATH")));
int n = Integer.parseInt(bufferedReader.readLine().trim()); String result = Result.largestNumber(n);
        bufferedWriter.write(result);
        bufferedWriter.newLine();
        bufferedReader.close();
        bufferedWriter.close();
    }
}

Here is the result of the screenshot.

Result

Answer

All you have to do is repeat the digit “9” n times, with the exception of returning -1 for 0.

public static String largestNumber(int n) {
     if(n == 0) return "-1";
     // for Java 11+: return "9".repeat(n);
     StringBuilder sb = new StringBuilder(n);
     for(int i = 0; i < n; i++) sb.append('9');
     return sb.toString();
}