[Programming Problem] Largest Number

Given a list of non-negative integers nums, arrange them such that they form the largest number and return it.
 
Since the result may be very large, so you need to return a string instead of an integer.
 
Example 1:
Input: nums = [10,2]
Output: "210"
 
Example 2:
Input: nums = [3,30,34,5,9]
Output: "9534330"

Take two numbers, say 3 and 30. How would you decide which one would come first? You would simply compare ‘330’ and ‘303’ and decide.

Given the above comparison function, we simply sort these numbers using a custom comparator which compares two numbers in the above way. Then, just concat array and return number.

One gotcha: the system expects you to remove leading zeros. We use a regex for that.

/**
 * @param {number[]} nums
 * @return {string}
 */
var largestNumber = function(nums) {
    nums.sort((a, b) => Number(a+""+b) > Number(b+""+a) ? -1 : 1);
    return nums.join("").replace(/^0*(.+)/, '$1');
};

Leave a Reply

Your email address will not be published.