题目描述
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.
思路
主要是排序函数,cmp。
代码
class Solution {
public:
static bool cmp(int a, int b) {
return to_string(a)+to_string(b) > to_string(b)+to_string(a);
}
string largestNumber(vector<int>& nums) {
sort(nums.begin(), nums.end(), cmp);
if (nums[0] == 0) return "0";
string ans = "";
for (int i=0; i<nums.size(); ++i) {
ans += to_string(nums[i]);
}
return ans;
}
};