lintcode-medium-Largest Number
Given a list of non negative integers, arrange them such that they form the largest number.
Given [1, 20, 23, 4, 8]
, the largest formed number is 8423201
.
public class Solution { /** *@param num: A list of non negative integers *@return: A string */ public String largestNumber(int[] num) { // write your code here if(num == null || num.length == 0) return ""; String[] strs = new String[num.length]; for(int i = 0; i < num.length; i++) strs[i] = String.valueOf(num[i]); Arrays.sort(strs, new Comparator<String>(){ public int compare(String s1, String s2){ return (s2 + s1).compareTo(s1 + s2); } }); StringBuilder result = new StringBuilder(); for(int i = 0; i < strs.length; i++) result.append(strs[i]); while(result.length() > 1 && result.charAt(0) == '0') result.deleteCharAt(0); return result.toString(); } }