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 is very large, so you need to return a string instead of an integer.
This problem is still a certain difficulty, the key is how you want to sort the numbers, and then I think of a good way:
Like 85 and 859, who put it in front?
Let 85859 and 85985 compare, that is to say
Compare (int a,int b) {
Return Long.parselong (A + "" +b)-Long.parselong (A + "" +b);
}
So the rest is simple ~
Package Testandfun;import Java.util.arrays;import Java.util.comparator;public class Largestnumber {public static void Main (string[] args) {Largestnumber ln = new Largestnumber (); int[] in = {3, 2, SI, 9,, 859,};//sortnum (in); System.out.println (Ln.biggestnumber (in)); Sort by custom rule public static void Sortnum (int[] a) {int temp = 0;for (int i = a.length-1; i > 0; i.) {for (int j = 0; j < I; ++J) {if (compare (A[j+1],a[j]) <0) {temp = A[j];a[j] = a[j + 1];a[j + 1] = temp;}}}} Output public String biggestnumber (int[] num) {string output = new string (), Sortnum (num); for (int i = num.length-1; I >= 0; i--) {output + = Num[i] + "";} if (Output.length () >1 && output.charat (0) = = ' 0 ') return 0+ ""; return output;} collation public static int compare (int o1, int o2) {String S1 = O1 + "" + O2; String s2 = O2 + "" + o1;return (int) (Long.parselong (S1)-Long.parselong (S2));}}
"Leetcode" largest number