0 ms solution for compare version numbers


  • 1
    C
        class Solution {
    public:
        int compareVersion(string version1, string version2) {
            string A,B; 
            string A_ret= version1;
            string B_ret = version2;
            while(!A_ret.empty() && !B_ret.empty())
            {
                A = A_ret.substr(0, A_ret.find('.'));
                B = B_ret.substr(0, B_ret.find('.'));
                if(stoi(A) > stoi(B)) return 1;
                else if(stoi(A) < stoi(B)) return -1;
                else {
                    if(A_ret.find('.')!= string::npos && A_ret.find('.')+1!= A_ret.size())//find '.'
                        A_ret = A_ret.substr(A_ret.find('.')+1, A_ret.size()-A_ret.find('.')-1);
                    else
                    {
                        A = A_ret;
                        A_ret="";
                    }
                    if(B_ret.find('.')!= string::npos && B_ret.find('.')+1!= B_ret.size())//find '.'
                        B_ret = B_ret.substr(B_ret.find('.')+1, B_ret.size()-B_ret.find('.')-1);
                    else
                    {
                        B = B_ret;
                        B_ret = "";
                    }
                }
            }
            if((A_ret.empty() && B_ret.empty()))
            {
                if(stoi(B) == stoi(A)) return 0;
                else if(stoi(A) > stoi(B)) return 1;
                else return -1;
            }
            else if(A_ret.empty())
            {
                if(stoi(B_ret) == 0) return 0;
                else return -1;
            }
            else
            {
                if(stoi(A_ret) == 0) return 0;
                return 1;
            }
            
            
           
        }
    };

Log in to reply
 

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