# 179. Largest Number
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.
# Solution
Approach 1: Sorting via custom comparator.
# Code (Python)
Approach 1:
# Code (C++)
Approach 1:
// Sorting via custom comparator.
class Solution {
private:
static bool cmp(int a, int b) {
/*
ostringstream ossAB;
ostringstream ossBA;
ossAB << a << b;
ossBA << b << a;
return ossAB.str() > ossBA.str();
*/
string strA = to_string(a);
string strB = to_string(b);
return (strA + strB) > (strB + strA);
}
public:
string largestNumber(vector<int>& nums) {
std::sort(nums.begin(), nums.end(), cmp);
if (nums.size() == 0 || nums[0] == 0)
return "0";
ostringstream oss;
for (int i = 0; i < nums.size(); ++i)
{
oss << nums[i];
}
return oss.str();
}
};