This question is not easy

  • 2

    Especially in Java:

    To use customized comparator method, you need convert int[] to Integer[].
    When you compare two number, like "27" and "271", the simple way is to combine two numbers in different order like "27271" and "27127", then use a loop to check every digit.

    My solution for reference:

    public String largestNumber(int[] num) {
            Integer[] sorted = new Integer[num.length];
            for(int i=0;i<num.length;i++){
                sorted[i]= new Integer(num[i]);
            Arrays.sort(sorted, new Comparator<Integer>(){
                public int compare(Integer n1, Integer n2){
                    String l2 = Integer.toString(n2)+Integer.toString(n1);
                    String l1 = Integer.toString(n1)+Integer.toString(n2);
                    for(int i=0;i<l1.length();i++){
                        if(l1.charAt(i)>l2.charAt(i)) return 1;
                        else if(l1.charAt(i)<l2.charAt(i)) return -1;
                    return 0;
            StringBuilder sb = new StringBuilder();
            boolean flag = false;  // use a flag to eliminate the leading zero
            for(int i=sorted.length-1;i>=0;i--){
                if(sorted[i]!=0 && !flag) flag=true;
            if(!flag) sb.append('0');
            return sb.toString();

  • 3

    My java short code, basically we have the same idea.

    public class Solution {
        public String largestNumber(int[] num) {
            String[] str=new String[num.length];
            for(int i=0;i<num.length;i++) str[i]=String.valueOf(num[i]);
            Arrays.sort(str,new Comparator<String>(){
                public int compare(String s1,String s2){
            if(str[0].equals("0")) return "0";
            StringBuilder res=new StringBuilder();
            for(int i=0;i<num.length;i++){
            return res.toString();

  • 0

    That's great!

    Here is a slightly different way to override the compare method

    return Long.valueOf(s2+s1).compareTo(Long.valueOf(s1+s2));

Log in to reply

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.