5 lines solution in JavaScript


  • 12
    L
    function largestNumber(num) {
        return num.sort(function(a, b) {
            return (b + '' + a ) - (a + '' + b);
        }).join('').replace(/^0*/,'') || '0';
    }

  • 0
    B
    This post is deleted!

  • 0
    B

    can you explain how the the inner function work?


  • 1
    L

    Hi @brianho1023,

    sorry for the late reply, the inner function does below:

    1. it sorts (num.sort) all the numbers with a given sorter (function (a, b))
    2. it concatenates (.join) all sorted numbers
    3. it removes leading extra '0' if any (replace)
    4. if the concatenated string is empty, return '0' instead

    And the sorter is quite simple: compare by a concatenated b with b concatenated a, for example if a is 3 and b is 4, then we compare 34 with 43.


Log in to reply
 

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