Share my c++ 19 ms solution with comp function


  • 3
    D

    generally I used the comp function.
    Please note:

    1. deal with zero (all zero's and some zeros)
    2. the comp function promoted to long long type to avoid overflow.
    class Solution {
    private:
        static bool sortFunction(long long n1, long long  n2) {
            int d1 = 1, d2 = 1;
            while(d1 <= n1) d1 *= 10;
            while(d2 <= n2) d2 *= 10;
            return  (n1 * d2 + n2) < (n2 * d1 + n1);
        }
    public:
        string largestNumber(vector<int> &num) {
            int n = num.size();
            sort(num.begin(), num.end());
            if(n < 1 || 0== num[n -1]) return "0";
            int index ;
            for(int i = 0; i < n; i++){
                if(0 != num[i]){
                    index = i; 
                    break;
                }
            }
            sort(num.begin() + index, num.end(), sortFunction);
            string result;
            for(int i = num.size() -1 ; i >= 0; i--){
                result += to_string(num[i]);
            }
            return result;
        }
    };

Log in to reply
 

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