Given a set of non-negative integers, rearrange their order to form the largest integer.
Example 1:
input:[10,2]
output:210
Example 2:
input:[3,30,34,5,9]
output:9534330
Explanation: The output result can be very large, so you need to return a string instead of an integer.
I have written a comparison function for a long time, and the clock is defective. I saw this very clever comparison method on the Internet.
bool cmp(string a, string b){ return a+b>b+a; }
Such a short program can achieve the largest combination, but it's still too bad.
#include<algorithm> class Solution { public: static bool cmp(string a, string b){ return a+b>b+a; } string largestNumber(vector<int>& nums) { vector<string> ans; for(int i = 0; i < nums.size(); i++) ans.push_back(to_string(nums[i])); sort(ans.begin(), ans.end(), cmp); string res = ""; for(int i = 0; i < nums.size();i++) res += ans[i]; if(res[0] == '0') res = "0"; return res; } };