C++ 4ms Solution, By comparing each part of the string that is separated with '.'


  • 1
    G

    Compare each part of the string that is separated with '.'

    If ">" or "<" return 1 or -1, otherwise, compare next separated part.

    class Solution {
    public:
        int compareVersion(string version1, string version2) {
            int num1, num2;
            int i=0, j=0;
            while (i<version1.size() || j<version2.size()) {
                num1 = 0; num2 = 0;
                while(version1[i]!='.' && i<version1.size()) {
                    num1 = num1*10+version1[i]-'0';
                    i++;
                }
                while(version2[j]!='.' && j<version2.size()) {
                    num2 = num2*10+version2[j]-'0';
                    j++;
                }
                if (num1>num2)
                    return 1;
                if (num1<num2)
                    return -1;
                i++;
                j++;
                
            }
            return 0;
        }
    };

  • 6
    J

    You may have overflow problems....


Log in to reply
 

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