Online Judge Solutions

Monday, December 15, 2014

Compare Version Numbers

Compare two version numbers version1 and version1.
If version1 > version2 return 1, if version1 < version2 return -1, otherwise return 0.

You may assume that the version strings are non-empty and contain only digits and the . character.
The . character does not represent a decimal point and is used to separate number sequences.

For instance, 2.5 is not "two and a half" or "half way to version three", it is the fifth second-level revision of the second first-level revision.

Here is an example of version numbers ordering:
0.1 < 1.1 < 1.2 < 13.37
 
class Solution {
public:
    int compareVersion(string version1, string version2) {
        int i = 0, j = 0;
        int va = 0;
        int vb = 0;
        
        while(i < version1.length() || j < version2.length()) {
           while(i < version1.length() && version1[i] != '.')
             va = 10*va + version1[i++] - '0';
           i++; // skip '.'
           
           while(j < version2.length() && version2[j] != '.')
             vb = 10*vb + version2[j++] - '0';
           j++; // skip '.'
           
           if (va != vb) break;
           
           // reset to start new pair of numbers
           va = 0;
           vb = 0;
        }
        
        if (va == vb) return 0;
        return va > vb ? 1 : -1;
    }
};

No comments:

Post a Comment