Skip to content

Commit 75f14bd

Browse files
committed
Create LargestNumber.cc
1 parent 5c2b42f commit 75f14bd

1 file changed

Lines changed: 28 additions & 0 deletions

File tree

cpp/LargestNumber.cc

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
2+
class Solution {
3+
public:
4+
string largestNumber(vector<int> &num) {
5+
vector<string> strs;
6+
for (auto i: num) {
7+
strs.push_back(to_string(i));
8+
}
9+
10+
sort(strs.begin(), strs.end(), [](const string& s1, const string& s2) { return s1 + s2 > s2 + s1;}); // note we want desc order
11+
string res = "";
12+
int i = 0; // ignore leading 0s
13+
while (i < strs.size() && strs[i] == "0") {
14+
i++;
15+
}
16+
17+
// if all "0", ...
18+
if (i == strs.size()) {
19+
return "0";
20+
}
21+
22+
for (; i < strs.size(); i++) {
23+
res += strs[i];
24+
}
25+
26+
return res;
27+
}
28+
};

0 commit comments

Comments
 (0)