码迷,mamicode.com
首页 > 编程语言 > 详细

[LeetCode][JavaScript]Largest Number

时间:2015-07-06 14:09:52      阅读:130      评论:0      收藏:0      [点我收藏+]

标签:

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 };

 

 

 

 

[LeetCode][JavaScript]Largest Number

标签:

原文地址:http://www.cnblogs.com/Liok3187/p/4624153.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!