-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathlargest-number.cpp
More file actions
41 lines (38 loc) · 867 Bytes
/
largest-number.cpp
File metadata and controls
41 lines (38 loc) · 867 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
// 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.
//
class Solution {
public:
string largestNumber(vector<int>& nums) {
auto cmp = [](int a, int b) {
string sa = to_string(a);
string sb = to_string(b);
return sa+sb > sb+sa;
};
sort(nums.begin(), nums.end(), cmp);
stringstream ss;
for (auto&& i : nums) {
ss << i;
}
string ans = ss.str();
size_t i = 0;
while (ans[i] == '0' && i < ans.size()-1) {
++i;
}
return ans.substr(i);
}
};