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.
Credits:
Special thanks to @ts for adding this problem and creating all test cases.
public class Solution {
public String largestNumber(int[] nums) {
if (nums.length == 0) {
return "0";
}
String[] strs = new String[nums.length];
for (int i = 0; i < nums.length; i ++) {
strs[i] = nums[i] + "";
}
Arrays.sort(strs, new Comparator<String>() {
@Override
public int compare(String i, String j) {
String s1 = i + j;
String s2 = j + i;
return s1.compareTo(s2);
}
});
if (strs[strs.length - 1].charAt(0) == '0') {
return "0";
}
StringBuilder builder = new StringBuilder();
for (int i = strs.length - 1; i >= 0; i --) {
builder.append(strs[i]);
}
return builder.toString();
}
}