您的位置:首页 > 其它

LeetCode OJ 之 Largest Number (最大的数字)

2015-05-18 15:26 169 查看

题目:

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.
给定一个非负整型数组,重新组合它们使得结果最大。
注意:使用字符串存储最大的数字,防止溢出。

思路:

使用sort函数,自定义比较函数。

题目:

class MyGreat
{
public:
bool operator()(const int x ,const int y)  //自定义比较函数
{
string s1 = to_string(x) + to_string(y);
string s2 = to_string(y) + to_string(x);
return (s1.compare(s2) > 0);
}
};
class Solution {
public:
string largestNumber(vector<int>& nums)
{
sort(nums.begin() , nums.end() , MyGreat());
string result;
if(nums.empty())
return result;
for(int i = 0 ; i < nums.size() ; i++)
{
result += to_string(nums[i]);
}
if(result[0] == '0')    //如果首位为0,说明所有数字都是0,则返回0即可。
return "0";
else
return result;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐