题目描述:
Given a list of non negative integers, arrange them such that they form the largest number.
Example 1:
Input: [10,2]
Output: "210"
Example 2:
Input: [3,30,34,5,9]
Output: "9534330"
Note: The result may be very large, so you need to return a string instead of an integer.
将数组先排序,在首尾链接组成结果。当a在前,b在后组成的数小于b在前,a在后组成的数,说明a小于b。但是需要注意的是当结果最高位为0时,直接返回“0”。
class Solution {
public:
string largestNumber(vector<int>& nums) {
sort(nums.begin(),nums.end(),comp);
string result;
for(int i=0;i<nums.size();i++) result+=int2str(nums[i]);
if(result[0]=='0') return "0";
return result;
}
static bool comp(int a, int b)
{
if(int2str(a)+int2str(b)>int2str(b)+int2str(a)) return true;
else return false;
}
static string int2str(int a)
{
if(a==0) return "0";
string result;
while(a>0)
{
result=(char)((a%10)+'0')+result;
a/=10;
}
return result;
}
};