[leedcode 179] 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.
public class Solution { public String largestNumber(int[] nums) { //注意comp函数的写法,需要继承接口 //以及Arrays.sort参数的写法,需要把整数形式转化成字符串 //最后拼接res时,要从后向前拼接 //最后需要处理首位为0的情况 StringBuilder res=new StringBuilder(); if(nums==null||nums.length<=0) return res.toString(); String[] strs=new String[nums.length]; for(int i=0;i<nums.length;i++){ strs[i]=""+nums[i]; } Arrays.sort(strs, new myComparator()); for(int i=nums.length-1;i>=0;i--){ res.append(strs[i]); } int i=0;//注意0,0,0的输入 while(i<res.length()-1&&res.charAt(i)=='0')i++; return res.toString().substring(i); } public class myComparator implements Comparator<String>{ public int compare(String a,String b){ return (a+b).compareTo(b+a); } } }