My 28ms C++ solution: using sort but self-defined the comparison function


  • 0
    T
    bool comparison(int i, int j)
    {
        string string1 = to_string(i) + to_string(j);
        long int v1 = atol(string1.c_str());
        string string2 = to_string(j) + to_string(i);
        long int v2 = atol(string2.c_str());
        return (v1>v2);
    };
        
    class Solution {
    public:
        string largestNumber(vector<int>& nums) {
            sort(nums.begin(), nums.end(), comparison);
            string s;
            int i, n=nums.size();
            if(n==0)
                return s;
            int j;
            for(i=0; i<n; i++)
                if(nums[i] > 0)
                    break;
            for(j=i; j<n; j++)
                s = s + to_string(nums[j]);
            if(s.length() == 0)
                s = s + '0';
            return s;
        }
    };

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.