Largest Number - Codeprg

Breaking

programing News Travel Computer Engineering Science Blogging Earning

Thursday 17 September 2020

Largest Number

 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.


class Solution {

public:

    string largestNumber(vector<int>& nums) {

        

        vector<string> mp;

        for(auto x:nums)

        {

            mp.push_back(to_string(x));

        }

        sort(mp.begin(),mp.end(),[](const string &a,const string &b)->bool{

            return a+b>b+a;

        });

        string res="";

        for(auto s:mp)

            res+=s;

        int i=0;

            while(res[i]=='0'&&res.size()>1)

             res.erase(0,1);

        return res;

    }

};