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.

Solution:

public class Solution {
    public String largestNumber(int[] nums) {
        String[] strs = new String[nums.length];
        for(int i=0; i<nums.length; i++) strs[i] = ""+nums[i];
        Arrays.sort(strs, new Comparator<String>(){
           @Override
           public int compare(String a, String b){
               String sA = a + b;
               String sB = b + a;
               return sA.compareTo(sB);
           }
        });
        StringBuilder sb = new StringBuilder();
        for(int i=strs.length-1; i>=0; i--){
            sb.append(strs[i]);
        }
        return strs[strs.length-1].equals("0") ? "0" : sb.toString();
    }
}
comments powered by Disqus