Largest Number
Given a list of non negative integers, arrange them such that they form the largest number.
Example 1:
Input: [10,2]
Output: "210"
Example 2:
Input: [3,30,34,5,9]
Output: "9534330"
Note: The result may be very large, so you need to return a string instead of an integer.
Solution:
class Solution {
public String largestNumber(int[] nums) {
List<String> strs = new ArrayList();
for (int n : nums) {
strs.add(Integer.toString(n));
}
Collections.sort(strs, (a, b) -> {
String aB = a + b;
String bA = b + a;
return bA.compareTo(aB);
});
StringBuilder sb = new StringBuilder();
for (String s : strs) {
if (sb.length() > 0 && sb.charAt(0) == '0' && s.equals("0")) {
continue;
}
sb.append(s);
}
return sb.toString();
}
}