[c++]My ac solution with 2ms


  • 4
    S
      class Solution {
        public:
            int compareVersion(string version1, string version2) {
                int size1 = version1.size();
                int size2 = version2.size();
                // split version
                int sum1,sum2,i,j;
                for(i = 0,j = 0;i < size1 || j < size2;++i,++j){
                    // version1
                    sum1 = 0;
                    while(i < size1 && version1[i] != '.'){
                        sum1 = sum1 * 10 + version1[i] - '0';
                        ++i;
                    }//while
                    // version2
                    sum2 = 0;
                    while(j < size2 && version2[j] != '.'){
                        sum2 = sum2 * 10 + version2[j] - '0';
                        ++j;
                    }//while
                    // compare
                    if(sum1 > sum2){
                        return 1;
                    }//if
                    else if(sum1 < sum2){
                        return -1;
                    }//else
                }//for
                return 0;
            }
        };

  • 2
    Y

    Hi there,
    This code should be wrong, since these two numbers could a very large numbers.
    So your code may have overflow.
    Try this test case version1("999999999999");
    version2("1");


  • 0
    F

    although such case above maybe wrong, it is indeed a great way to solve. you teach me to use one "||" and two "while" in a "for" loop so that two conditions can run together to save time! thank you!


  • 0
    R

    For a version number, I think it's reasonable to assume an integer is big enough to represent it.


  • 0
    S

    This is a valid concern. Apparently Leetcode does't have a test case like this.


  • 0
    W

    i also think so...
    overflow should be considered

    leetcode always doesn't have a clear statement


Log in to reply
 

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