题目:
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;
}
};