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(int[] nums) { int len = nums.length; if (len < 1) { return ""; } String[] strs = new String[len]; for (int i = 0; i < len; i++) { strs[i] = String.valueOf(nums[i]); } Arrays.sort(strs, new Comparator<String>() { @Override public int compare(String o1, String o2) { // TODO Auto-generated method stub return (o1 + o2).compareTo(o2 + o1); } }); StringBuffer res = new StringBuffer(); for (int i = len-1; i >= 0; i--) { res.append(strs[i]); } int i = 0; while (i < len && res.charAt(i) == ‘0‘) { i++; } if (i == len) { return "0"; } return res.substring(i).toString(); } }
?
原文:http://hcx2013.iteye.com/blog/2251754