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.

// Convert from int to string and sort
string largestNumber(vector<int>& nums) { // time: O(nlogn); space: O(n * str_len)
    sort(nums.begin(), nums.end(), [](const int& n1, const int& n2) {
        string s1 = to_string(n1), s2 = to_string(n2);
        return (s1 + s2) > (s2 + s1);
    });
    if (to_string(nums[0])[0] == '0') return "0";
    string res;
    for (const int& num : nums) {
        res += to_string(num);
    }
    return res;
}

Last updated

Was this helpful?