Largest Number

Given a list of non negative integers, arrange them such that they form the largest number.

For example:

Given [3, 30, 34, 5, 9], the largest formed number is 9534330.

Note: The result may be very large, so you need to return a string instead of an integer.

public class Solution {
    public String largestNumber(final int[] A) {
        if (A.length == 0) 
            return "";
        
        String[] st = new String[A.length];
        for (int i = 0; i < A.length; i++) 
            st[i] = Integer.toString(A[i]);
        
        Arrays.sort(st, (s1, s2) -> (s2 + s1).compareTo(s1 + s2));
        StringBuilder sb = new StringBuilder();
        for (String s : st)
            sb.append(s);

        String ans = sb.toString();
        if (ans.charAt(0) == '0') 
            return "0";
        
        return ans;
    }
}

Last updated