Problem statement is to form largest number from a given int array. For e.g. if the input array is {3, 30, 34, 5, 9} then the result should be 9534330. I tried following code but I am getting an exception in the if condition where I am trying to parse string into an int. Can you please tell how to resolve this?
import java.util.*;
import java.lang.Integer;
public class Console2 {
public static void largestNumber(int[] array) {
int s = array.length;
String result = "0";
for (int i = 0; i < s; i++) {
int[] temp = new int[s];
temp[i] = array[i];
for (int j = 0; j < s; j++) {
if ( i != j) {
temp[j] = array[j];
}
}
if (Integer.parseInt(temp.toString()) > Integer.parseInt(result)) { // getting exception here !!!
/*
in the inner for loop, the temp array will store possible combinations of elements of
the input array. so if i convert the temp array into string and then parse it to int, then
i should be able to compare it with a result string (parsed to int) and store the highest
possible number as string. once the outer for loop completes, the result will have highest
formed number which gets printed in this method.
*/
result = temp.toString();
}
}
System.out.println(result);
}
public static void main(String[] args) {
int[] array = {3, 30, 34, 5, 9};
largestNumber(array);
}
}
Exception message:
Exception in thread "main" java.lang.NumberFormatException: For input string: "[I@7cc355be"
at java.base/java.lang.NumberFormatException.forInputString(NumberFormatException.java:68)
at java.base/java.lang.Integer.parseInt(Integer.java:652)
at java.base/java.lang.Integer.parseInt(Integer.java:770)
at Console2.largestNumber(Console2.java:15)
at Console2.main(Console2.java:23)