Share my concise solution


  • 1
    S

    in facet this problem is kind of sort problem, the steps are: firstly sort all the elements, then get the result

    static bool compare(int a, int b) {
        string s1 = to_string(a), s2 = to_string(b);
        int m = s1.size(), n = s2.size();
        
        for (int i = 0, j = 0; i < m && j < n; ) {
            if (s1[i] != s2[j]) return s1[i] < s2[j];   // not equal
            if (i == m - 1 && j == n - 1) return false; // equal
            else if (i == m - 1) { i = 0; ++j; }        // i back to begin
            else if (j == n - 1) { j = 0; ++i; }        // j back to begin
            else { ++i; ++j; }
        }
    }
    
    string largestNumber(vector<int> &num) {
        string ans;
        sort(num.begin(), num.end(), compare);
        
        for (auto i : num) ans = to_string(i) + ans;
        if (ans[0] == '0') return "0";
        return ans;
    }

  • 0
    N

    Simple code with strong Readability !


Log in to reply
 

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