给定一组非负整数,重新排列它们的顺序使之组成一个最大的整数。
示例 1:
输入:[10,2]
输出:210
示例 2:
输入:[3,30,34,5,9]
输出:9534330
说明: 输出结果可能非常大,所以你需要返回一个字符串而不是整数。
解题思路:
对数组中的元素进行排序,判断是‘a’ + 'b' 组合大 还是‘b’ +‘a’ 组合大,最后要注意输入全是‘0’的情况只返回一个‘0’
class Solution {
public:
string largestNumber(vector<int>& nums) {
string res;
sort(nums.begin(), nums.end(), cmp);
for(auto &i : nums){
res += to_string(i);
}
return atoi(res.c_str()) == 0 ? to_string(0) : res; // 如果res全是‘0’, 只输出一个0
}
static bool cmp(const int x,const int y){
int sizex = to_string(x).size(); // x的位数
int sizey = to_string(y).size(); // y的位数
return (x * pow(10, sizey) + y) > (y * pow(10, sizex) + x);
}
};