179. Largest Number

179. Largest Number

Description

Given a list of non-negative integers nums, arrange them such that they form the largest number and return it.

Since the result may be very large, so you need to return a string instead of an integer.

Example 1:

1
2
Input: nums = [10,2]
Output: "210"

Example 2:

1
2
Input: nums = [3,30,34,5,9]
Output: "9534330"

Constraints:

  • 1 <= nums.length <= 100
  • 0 <= nums[i] <= 10^9

Hints/Notes

Solution

Language: C++

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
class Solution {
public:
string largestNumber(vector<int>& nums) {
auto cmp = [](const int l, const int r) {
string lhs = to_string(l), rhs = to_string(r);
return lhs + rhs > rhs + lhs;
};
sort(nums.begin(), nums.end(), cmp);
if (nums[0] == 0) {
return "0";
}
string res;
for (int i = 0; i < nums.size(); i++) {
res += to_string(nums[i]);
}
return res;
}
};