### Problem

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

### 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 problem can be solve by simply sorting strings, not sorting integer. Define a comparator to compare strings by concat() right-to-left or left-to-right.

### JavaScript Code

function largestNumber(num) { var NUM = []; var res = ''; for (var i = 0; i <num.length; i++) { NUM.push(num[i]+''); } NUM.sort(function (a, b) { var leftRight = a+b; var rightLeft = b+a; if (leftRight > rightLeft) { return -1; } if (leftRight < rightLeft) { return 1; } return 0; }); for (var i = 0; i < NUM.length; i++) { res += NUM[i]; } return parseInt(res); } console.log(largestNumber([3, 30, 34, 5, 9]));

## 0 comments:

## Post a comment