Share my method(C++ version), running time: 10ms


  • -1
    G

    class Solution {

    public:

    static bool compare(unsigned int left, unsigned int right) {
        unsigned int left_temp      = left;
        unsigned int right_temp     = right;
        unsigned int Left_Multiply  = 1;
        unsigned int Right_Multiply = 1;
        unsigned long long Combine_Left_Right = 0;
        unsigned long long Combine_Right_Left = 0;
    
        //
        // If Input is zero can accelerate processing time
        //
        if (left == 0) {
            return false;
        }
        if (right == 0) {
            return true;
        }
    
        //
        // Calculate each number's length
        //
        do {
            Left_Multiply  = (left_temp != 0)   ? Left_Multiply * 10  : Left_Multiply;
            Right_Multiply = (right_temp != 0)  ? Right_Multiply * 10 : Right_Multiply;
            left_temp      = left_temp / 10;
            right_temp     = right_temp / 10;
        } while((left_temp != 0) || (right_temp != 0));
    
        //
        // Use combine method, to find the largest number
        //
        Combine_Left_Right = left  * Right_Multiply + right;
        Combine_Right_Left = right * Left_Multiply  + left;
    
        return Combine_Left_Right > Combine_Right_Left;
    }
    
    string largestNumber(vector<int> &num) {
        string result = "";
        sort(num.begin(), num.end(), compare);
        //
        // Largest number string generator
        //
        for (int i=0; i<num.size(); i++) {
            stringstream DigitaltoString;
            DigitaltoString << num[i];
            result.append(DigitaltoString.str());
            //
            // Avoid the input is always zero
            //
            if (num[0] == 0) {
                break;
            }
        }
        return result;
    }
    

    };


Log in to reply
 

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