Largest Number
Description
Given a list of non negative integers, arrange them such that they form the largest number.
Example 1:
Input:[10,2]
Output: "210"
Example 2:
Input:[3,30,34,5,9]
Output: "9534330"
Note: The result may be very large, so you need to return a string instead of an integer.
Solution(javascript)
/**
* @param {number[]} nums
* @return {string}
*/
const largestNumber = function (nums = []) {
nums.sort((a, b) => {
const digitsA = a.toString(10) + b.toString(10)
const digitsB = b.toString(10) + a.toString(10)
for (let i = 0; i < digitsA.length; i++) {
const digitB = parseInt(digitsB[i], 10)
const digitA = parseInt(digitsA[i], 10)
if (digitB > digitA || digitB < digitA) {
return digitB - digitA
}
}
return 0
})
const result = nums.join('')
return result[0] === '0' ? '0' : result
}