首页 > 其他 > 详细

Largest Number

时间:2015-10-03 06:06:49      阅读:149      评论:0      收藏:0      [点我收藏+]

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.

 

Analyse: Write the sort compare function.

Runtime: 24ms

 1 class Solution {
 2 public:
 3     string largestNumber(vector<int>& nums) {
 4         string result;
 5         if(nums.empty()) return result;
 6         
 7         sort(nums.begin(), nums.end(), compare);
 8         for(int i = 0; i < nums.size(); i++)
 9             result += to_string(nums[i]);
10         
11         if(result[0] == 0) return "0";
12         return result;
13     }
14     
15     static int compare(int a, int b){
16         string s1 = to_string(a) + to_string(b);
17         string s2 = to_string(b) + to_string(a);
18         return s1 > s2;
19     }
20 };

 

Largest Number

原文:http://www.cnblogs.com/amazingzoe/p/4852997.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!