A simple C++ solution of 4ms


  • 1
    Y
    inline long long catnum(int a,int b)
    {
        if(a==0)
            return b;
        
        long long dec=1;
        if(b<10)
            dec=10;
        else if(b<100)
            dec=100;
        else if(b<1000)
            dec=1000;
        else if(b<10000)
            dec=10000;
        else if(b<100000)
            dec=100000;
        else if(b<1000000)
            dec=1000000;
        else if(b<10000000)
            dec=10000000;
        else if(b<100000000)
            dec=100000000;
        else if(b<1000000000)
            //   123456789
            dec=1000000000;
        else//   123456789x
            dec=10000000000LL;
        
        return dec*a+b;
    }
    
    bool comp(int a,int b){
        long long A=catnum(a,b);
        long long B=catnum(b,a);
        return A>B;
    }
    
    /*
    static char tmp[32];
    bool comp(int a,int b){
        sprintf(tmp,"%d%d",a,b);
        long long A=atoll(tmp);
        
        sprintf(tmp,"%d%d",b,a);
        long long B=atoll(tmp);
        
        return A>B;
    }
    */
    
    class Solution {
    public:
        string largestNumber(vector<int>& nums) {
            sort(nums.begin(),nums.end(),comp);
            
            stringstream ss(ios_base::out);
            
            bool zero=true;
            for(vector<int>::iterator it=nums.begin();it!=nums.end();++it){
                if(zero && *it==0)
                    ;
                else{
                    ss<<*it;
                    zero=false;
                }
            }
            if(zero)
                return "0";
            return ss.str();
        }
    };

Log in to reply
 

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