A 0ms C++ Solution without using atoi or other function


  • 0
    Y

    Algorithm is to compare each number between dot sign, "getnum" function inputs string and start position and returns a vector containing the number extract from the start position to the next dot and the next dot position. Be careful of the version string that number 0 got after the dot, which means the version is the same.

    class Solution {
    public:
        int compareVersion(string version1, string version2) {
            int len1 = version1.length();
            int len2 = version2.length();
            int i, j;
            int ans = INT_MAX;
            for(i = 0, j  = 0; (i < len1)&&(j < len2); i++, j++) {
                vector<int> res1,res2;
                res1 = getnum(version1,i);
                res2 = getnum(version2,j);
                if(res1[0] > res2[0]) return 1;
                if(res1[0] < res2[0]) return -1;
                if(res1[0] == res2[0]) {
                    i = res1[1];
                    j = res2[1];
                    if((i == len1)&&(j == len2)) return 0;
                }
            }
            if((j > len2)&&(i < len1)) {
                vector<int> res;
                res = getnum(version1, i);
                if(res[0] == 0) ans = 0;
                else ans = 1;
            }
            if((j < len2)&&(i > len1)) {
                vector<int> res;
                res = getnum(version2, j);
                if(res[0] == 0) ans = 0;
                else ans = -1;
            }
            if((j == len2)&&(i == len1)) ans = 0;
            return ans;
        }
    
        vector<int> getnum(string str, int pos) {
            bool flag = true;
            double sum = 0;
            vector<int> ans;
            int i = pos;
            for(i = pos; i < str.length(); i++) {
                if(str[i] == '.') break;
                sum = sum*10 + str[i] - '0';
            }
            ans.push_back(sum);
            ans.push_back(i);
            return ans;
        }
    };

Log in to reply
 

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