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.
Difficulty: Medium
public class Solution {
public String largestNumber(int[] nums) {
String[] list = new String[nums.length];
for(int i = 0; i < nums.length; i++){
list[i] = Integer.toString(nums[i]);
}
Arrays.sort(list, new Comparator<String>(){
public int compare(String s1, String s2){
String leftRight = s1+s2;
String rightLeft = s2+s1;
return -leftRight.compareTo(rightLeft);
}
});
String ans = "";
for(String str : list){
ans = ans + str;
}
if(ans.length() == 0 || ans.charAt(0) == '0')
return "0";
return ans;
}
}