Share my C++ solution,very easy to understand


  • 2
    V
    class Solution {
    public:
        string largestNumber(vector<int>& nums) {
            string ret;
            int n = nums.size();
            if (n == 0)
                return ret;
                
            sort(nums.begin(), nums.end(), my_cmp);
            
            for (int i = 0; i < n; i++)
                ret += to_string(nums[i]);
            
            if (ret[0] == '0')
                return "0";
            
            return ret;
        }
        
        static bool my_cmp(const int a, const int b)
        {
            string s_a = to_string(a);
            string s_b = to_string(b);
            
            return (s_a + s_b) > (s_b + s_a);
        }
    };
    

Log in to reply
 

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