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.
1 class NumbersComparator implements Comparator<String> { 2 @Override 3 public int compare(String s1, String s2) { 4 return (s2 + s1).compareTo(s1 + s2); 5 } 6 } 7 8 public class Solution { 9 10 public String largestNumber(int[] nums) { 11 String[] strs = new String[nums.length]; 12 for (int i = 0; i < nums.length; i++) { 13 strs[i] = Integer.toString(nums[i]); 14 } 15 Arrays.sort(strs, new NumbersComparator()); 16 StringBuilder sb = new StringBuilder(); 17 for (int i = 0; i < strs.length; i++) { 18 sb.append(strs[i]); 19 } 20 String result = sb.toString(); 21 int index = 0; 22 while (index < result.length() && result.charAt(index) == '0') { 23 index++; 24 } 25 if (index == result.length()) { 26 return "0"; 27 } 28 return result.substring(index,result.length()); 29 } 30 }