-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLargest_Number.cpp
More file actions
34 lines (30 loc) · 889 Bytes
/
Copy pathLargest_Number.cpp
File metadata and controls
34 lines (30 loc) · 889 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
#include <string>
#include <vector>
#include <algorithm>
// sort by comparing which order of strings gives the largest integer value
class Solution {
public:
struct sortByDigit {
bool operator()(std::string& a, std::string& b) {
return a+b > b+a;
}
};
std::string largestNumber(std::vector<int>& nums) {
std::string answer = "";
int len = nums.size();
std::vector<std::string> sortedStrings;
long totalSum = 0;
for (int i=0; i<len; i++) {
totalSum += nums[i];
sortedStrings.push_back(std::to_string(nums[i]));
}
if (totalSum == 0) {
return "0";
}
sort(sortedStrings.begin(), sortedStrings.end(), sortByDigit());
for (int i=0; i<len; i++) {
answer += sortedStrings[i];
}
return answer;
}
};