179. Largest Number

  • Difficulty: Medium

  • Topics: Sort

  • Similar Questions:

Problem:

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.

Solutions:

class Solution {
public:
    struct comparator {
        bool operator()(const string& a, const string& b) {
            return a + b > b + a; // not necessary to have stol;
        }
    };

    string largestNumber(vector<int>& nums) {

        vector<string> numStr;

        bool allZeros = true;

        for (auto num : nums) {
            if (num != 0)   allZeros = false;
            numStr.push_back(to_string(num));
        }

        if (allZeros == true)   return "0";

        sort(numStr.begin(), numStr.end(), comparator());
        string ret;
        for (auto& str : numStr) {
            ret.append(str);
        }

        return ret;
    }
};

results matching ""

    No results matching ""