Given a list of non negative integers, arrange them such that they form the largest number.


  • 0
    I

    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.

    This is my answer right now, but it doesn't work. HELPP

    public String largestNumber(int[] num) {
    int n = num.length;
    String[] a = new String[n];
    if (n < 1) return "";

         // convert to string
        for(int i=0; i < n; i++){
            a[i] = Integer.toString(i);
        }
        
        String result;  
        String e;
        for(int g = 0; g< n; g++)
        {
            String d = a[g];
            if(! ((g+1) >= n))
                e = a[g+1];
                
            // compare which concocted results in a bigger number
            if( Integer.parseInt(e+result) > Integer.parseInt(result+e) )
                result = e+result;
            else
                result = result+e;
                
        }
    
        return result;

Log in to reply
 

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