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.
class Solution {
public:static bool cmp(const string &s1, const string &s2)
{
return (s1 + s2) < (s2 + s1);
}
string largestNumber(vector<int> &nums) {
vector<string> strs;
string result;
for(int i=0;i<nums.size();i++)
{
strs.push_back(to_string(nums[i]));
}
sort(strs.begin(), strs.end(),cmp) ;
for(int j=strs.size()-1;j>=0;j--)
result+=strs[j];
if(result[0]=='0') return result='0';
else return result;
}
};
此题肯定要转换成string再排序满足要求,但是会碰到首字母相同,如何排序的问题,纠结了一天,发现用sort函数的CMP完美解决。