[LeetCode][JavaScript]Largest Number

Largest Number

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

For 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.

https://leetcode.com/problems/largest-number/

 

 


 

 

排序的时候把两个数拼起来试一试才知道谁大谁小。

有个[0,0]的case,太毒了。

 1 /**
 2  * @param {number[]} nums
 3  * @return {string}
 4  */
 5 var largestNumber = function(nums) {
 6     nums = nums.sort(sorting);
 7     var count = 0;
 8     for(var i = 0; i < nums.length - 1; i++){
 9         if(nums[i] === 0 ){
10             count++;
11         }else{
12             break;
13         }
14     }
15     while(count--){
16         nums.shift();
17     }
18     return nums.join('');
19 
20     function sorting(a, b){
21         a = a.toString();
22         b = b.toString();
23         if(parseInt(a + b) > parseInt(b + a)){
24             return -1;
25         }else if(parseInt(a + b) < parseInt(b + a)){
26             return 1;
27         }else{
28             return 0;
29         }
30     }
31 };

 

 

 

 

posted @ 2015-07-06 13:19  `Liok  阅读(323)  评论(0编辑  收藏  举报