标签:
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 n=nums.length; if(n<1){ return ""; } String[] strs = new String[n]; for(int i=0; i<nums.length; i++){ strs[i]=Integer.toString(nums[i]); } Arrays.sort(strs, new Cmp()); String ans=""; for(int i=n-1; i>=0; i--){ ans=ans+strs[i]; } //remove 0‘s in fornt of the string int i=0; while(i<ans.length() && ans.charAt(i)==‘0‘){ i++; } if(i == ans.length()){ return "0"; } return ans.substring(i); } private class Cmp implements Comparator<String>{ public int compare(String a, String b){ String ab=a+b; String ba=b+a; return ab.compareTo(ba); } } }
标签:
原文地址:http://www.cnblogs.com/incrediblechangshuo/p/5675202.html