Simple and straightforward C++ solution (0 ms)


  • 0
    B

    The basic idea is comparing two version numbers at each level (separated by '.').

    class Solution {
    public:
        int compareVersion(string version1, string version2) {
            int i = version1.find('.');
            int j = version2.find('.');
            int a = 0, b = 0;
            
            while(1) {
                // Find the version number in the current level
                a = stoi(version1.substr(0, i));
                b = stoi(version2.substr(0, j));
                
                // Determine which is larger
                if (a > b) return 1;
                if (a < b) return -1;
                if (i == -1 && j == -1) return 0;
                
                // Re-set everything for the next loop
                if (i == -1) version1 = "0";
                else version1 = version1.substr(i + 1);
                
                if (j == -1) version2 = "0";
                else version2 = version2.substr(j + 1);
                
                a = b = 0;
                i = version1.find('.');
                j = version2.find('.');
            }
            
            return 0;
        }
    };
    

Log in to reply
 

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