Prob:
Sol:
class Solution {
public:
static bool sort_temp(int a, int b) {
string s1 = to_string(a) + to_string(b);
string s2 = to_string(b) + to_string(a);
return s1 < s2;
}
string largestNumber(vector<int> &num) {
string sol;
int size = num.size();
if (num.size() == 0)
return sol;
sort(num.begin(), num.end(), sort_temp);
if (num[size - 1] == 0)
return "0";
for (int i = size - 1; i >= 0; i--) {
sol.append(to_string(num[i]));
}
return sol;
}
};
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.
Sol:
class Solution {
public:
static bool sort_temp(int a, int b) {
string s1 = to_string(a) + to_string(b);
string s2 = to_string(b) + to_string(a);
return s1 < s2;
}
string largestNumber(vector<int> &num) {
string sol;
int size = num.size();
if (num.size() == 0)
return sol;
sort(num.begin(), num.end(), sort_temp);
if (num[size - 1] == 0)
return "0";
for (int i = size - 1; i >= 0; i--) {
sol.append(to_string(num[i]));
}
return sol;
}
};
No comments:
Post a Comment