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) {
String[] str= new String[nums.length];
for (int i = 0; i < nums.length; i++) {
str[i]= Integer.toString(nums[i]);
}
Arrays.sort(str, new LargestNumberComparator());
StringBuilder sb= new StringBuilder();
for (String s: str) {
sb.append(s);
}
String res= sb.toString();
int index=0;
while (index< res.length() && res.charAt(index)=='0') index++;
if (index== res.length()) return "0";
return res.substring(index);
}
}
class LargestNumberComparator implements Comparator<String>{
@Override
public int compare(String o1, String o2) {
return (o2+o1).compareTo(o1+o2);
}
}