C++ wow didn't realize you can compare str1+str2.. I looped through each characters


  • 0
    W
    int gcd(int a, int b)
    {
        for (;;)
        {
            if (a == 0) return b;
            b %= a;
            if (b == 0) return a;
            a %= b;
        }
    }
    
    int lcm(int a, int b)
    {
        int temp = gcd(a, b);
    
        return temp ? (a / temp * b) : 0;
    }
    
    bool myCompare(string str1, string str2)
    {
        for (int i = 0; i < lcm(str1.size(), str2.size()); i++)
        {
            if (str1[i % str1.size()] == str2[i % str2.size()]) continue;
            if (str1[i % str1.size()] < str2[i % str2.size()]) return true;
            break;
        }
    
        return false;
    }
    
    class Solution 
    {
    public:
        string largestNumber(vector<int>& nums) 
        {
            vector<string> numStrs;
            for (auto& num : nums)
                numStrs.push_back(std::to_string(num));
            sort(numStrs.begin(), numStrs.end(), myCompare);
            string result = "";
            for (int i = numStrs.size() - 1; i >= 0; i--)
                result += numStrs[i];
            
            if (!result.empty() && result[0] == '0')
                result = "0";
            return result;
        }
    };

Log in to reply
 

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