Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Showing an error to find max number string in array by combining elements in java

Problem: Given an array of numbers, arrange them in a way that it forms the largest value.
Given a list of non-negative integers nums, arrange them such that they form the largest number and return it.

Since the result may be very large, so you need to return a string instead of an integer.

Input:
[54, 546, 548, 60]
Output:
6054854654

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Code:

public class SortNumber {
    public static void main(String[] args) {
        int [] arr = {111311, 1113};
        sortArray(arr);
        
        for (int i = 0; i < arr.length; i++) {
            System.out.print(arr[i] + "");
        }
    }
    public static int[] sortArray(int[] arr){
        for (int i = 0; i < arr.length; i++) {
            for (int j = 0; j < arr.length; j++) {
                String a = "" + arr[i] + arr[j];
                String b = "" + arr[j] + arr[i];
                int x = Integer.parseInt(a);
                int y = Integer.parseInt(b);
                if(x > y){
                    int temp = arr[i];
                    arr[i] = arr[j];
                    arr[j] = temp;
                }
            }
        }
        return arr;
    }
}

                            

Input: [111311, 1113]
Output: 1113111311 (Giving an error for this)

Error:

Exception in thread "main" java.lang.NumberFormatException: For input string: "111311111311"
            at java.base/java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
            at java.base/java.lang.Integer.parseInt(Integer.java:652)
            at java.base/java.lang.Integer.parseInt(Integer.java:770)
            at SortNumber.sortArray(SortNumber.java:15)
            at SortNumber.main(SortNumber.java:4)

Can someone tell me how can I solve this error.

>Solution :

The number formed by concatenating the two array elements is too large to be stored in an int. You can use long or BigInteger instead, depending on how large the input can be.

long x = Long.parseLong(a);
long y = Long.parseLong(b);

Note, however, that it is not necessary to work with numeric types at all for this sort of problem. Think about how String representations can be manipulated instead.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading