Leetcode 179. Largest Number (Medium) (cpp)
Tag: Sort
Difficulty: Medium
/*
179. Largest Number (Medium)
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.
*/
class Solution {
public:
string largestNumber(vector<int>& nums) {
string res;
sort(nums.begin(), nums.end(), comp);
if (nums[0] == 0) return "0";
for (int num : nums)
res += to_string(num);
return res;
}
static bool comp(int i, int j) {
return to_string(i) + to_string(j) > to_string(j) + to_string(i);
}
};