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.
class Solution {
public:
static bool compare(int a, int b)
{
return (to_string(a)+to_string(b)).compare(to_string(b)+to_string(a)) > 0;
}
string largestNumber(vector<int> &num)
{
std::sort(num.begin(), num.end(), compare);
string result = "";
int i = 0;
while(num[i] == 0)
i++;
if(i >= num.size())
return "0";
for(; i < num.size(); i++)
{
result += to_string(num[i]);
}
return result;
}
};