Largest Number
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.
给定一个非负整型数组,重新安排它们的顺序使其组成的数字最大。例如,给定 [3, 30, 34, 5, 9],最大数字形式为 9534330
。
说明:结果可能很大,需要返回string代替int类型。
分析:
要使数最大,需要最高位越大越好,可将 int 转化成字符串,然后把字符串按降序排序,连接成的数字即为最大数。
注意全为 0 时结果只有一个 0。
class Solution {
public:
string largestNumber(vector<int>& nums) {
if(nums.empty())
{
return string();
}
int numsSize = nums.size();
vector<string> numsStr;
for(int index = 0; index < numsSize; ++index)//int 转化成 string
{
numsStr.push_back(to_string(nums[index]));
}
sort(numsStr.begin(), numsStr.end(), strDecComp);//对字符串从大到小排序
int strSize = numsStr.size();
int nzero = 0;
string sret;
for(int index = 0; index < strSize; ++index)
{
if(numsStr[index] != "0")
{
sret += numsStr[index];
}
else
{
++nzero;
}
}
if(nzero)
{
if(sret.empty())//全部是 0
{
sret += "0";
return sret;
}
while(nzero--)//不全是 0
{
sret += "0";
}
}
return sret;
}
//字符串比较函数,从大到小排序
static bool strDecComp(string& src, string& des)
{
return (src + des) > (des + src);
}
};