1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40
|
public class LargestNumber { public String largestNumber(int[] nums) { if (nums == null || nums.length == 0) { return ""; } String[] strings = new String[nums.length]; for (int i = 0; i < nums.length; i++) { strings[i] = String.valueOf(nums[i]); } Arrays.sort(strings, new Comparator<String>() { public int compare(String o1, String o2) { String s1 = o1 + o2; String s2 = o2 + o1; return -1 * s1.compareTo(s2); } }); StringBuilder sb = new StringBuilder(); for (String s : strings) { sb.append(s); } String result = sb.toString(); int i = 0; while (i < result.length() && result.charAt(i) == '0') { i++; } return i == result.length() ? "0" : result.substring(i, result.length()); } }
|