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.

 

ref http://blog.csdn.net/whuwangyi/article/details/42705317

"这题最简单的方法其实是,比较两个字符串s1和s2时,比较s1+s2和s2+s1即可。注意这里有一个特殊情况,就是组合后的字符串以0开始,需要把开始的0都去掉。"

对这个comparator的解法很不熟悉

学习一下

 

    public class StringComparator implements Comparator<String>{

        public int compare(String s1, String s2){

            String s12 = s1+s2;

            String s21 = s2+s1;

            return (int) (Long.parseLong(s12) - Long.parseLong(s21));

        }

    }

    public String largestNumber(int[] nums) {

        if(nums==null||nums.length==0) return null;

        List<String> list = new ArrayList<String>();

        StringBuilder sb =  new StringBuilder();

        for(int i:nums) list.add(""+i);

        Collections.sort(list, new StringComparator());

        if(list.get(list.size()-1).equals("0")) return "0";

        for(String i:list){

            sb.insert(0,i);

        }

        return sb.toString();

    }

 

你可能感兴趣的:(number)