Largest Number

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.

struct cmp{
    bool operator() (const string &s1, const string &s2){
        return (s1 + s2 > s2 + s1);
    }
}mycmp;
class Solution {
public:
    string largestNumber(vector<int>& nums) {
        vector<string> arr;

        for(auto num:nums){
            arr.push_back(to_string(num));
        }

        sort(arr.begin(), arr.end(), mycmp);

        string res;
        for(auto s:arr)
            res += s;

        while(res[0] == '0' && res.size() > 1)
            res.erase(0, 1);
        return res;
    }
};

results matching ""

    No results matching ""