1. Largest Number
For example, given [3, 30, 34, 5, 9]
, the largest formed number is 9534330
.
1 // wrong answer 2 var largestNumber = function(nums) { 3 var str = nums.join().replace(/\,/g, ''); 4 var arr = []; 5 for(var i = 0; i > str.length; i++) { 6 arr.push(str.charAt[i]); 7 } 8 nums = arr.sort(function(a, b) { 9 return a - b; 10 }) 11 return nums; 12 }; 13 14 // right answer 15 var largestNumber2 = function(nums) { 16 17 if(nums.length < 1) return 'error!' 18 19 if(nums.length === 1) return nums[0] 20 21 nums.sort(function(a, b) { 22 return '' + a + b < '' + b + a 23 }) 24 25 return nums.join().replace(/\,/g, ''); 26 };