[LeetCode] Compare Version Numbers

165. Compare Version Numbers

Given two version numbers, version1 and version2, compare them.

Version numbers consist of one or more revisions joined by a dot ‘.’. Each revision consists of digits and may contain leading zeros. Every revision contains at least one character. Revisions are 0-indexed from left to right, with the leftmost revision being revision 0, the next revision being revision 1, and so on. For example 2.5.33 and 0.1 are valid version numbers.

To compare version numbers, compare their revisions in left-to-right order. Revisions are compared using their integer value ignoring any leading zeros. This means that revisions 1 and 001 are considered equal. If a version number does not specify a revision at an index, then treat the revision as 0. For example, version 1.0 is less than version 1.1 because their revision 0s are the same, but their revision 1s are 0 and 1 respectively, and 0 < 1.

Return the following:

  • If version1 < version2, return -1.
  • If version1 > version2, return 1.
  • Otherwise, return 0.
  • new solution update 2022.02.25
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
class Solution {
int parse(string& s, int &i) {
int res = 0;
while(i < s.length() and s[i] != '.') {
res = res * 10 + (s[i++] & 0b1111);
}
i++;
return res;
}
public:
int compareVersion(string version1, string version2) {
int v1 = 0, v2 = 0;
while(v1 < version1.length() or v2 < version2.length()) {
int pv1 = parse(version1, v1);
int pv2 = parse(version2, v2);
if(pv1 > pv2) return 1;
else if(pv1 < pv2) return -1;
}
return 0;
}
};
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
class Solution {
public:
int compareVersion(string version1, string version2) {
int v1, v2, p1 = 0, p2 =0;
while(p1 < version1.length() || p2 < version2.length()) {
v1 = v2 = 0;
for(; p1 < version1.length() && version1[p1] != '.'; p1++){
v1 = (v1<<3) + (v1<<1) + (version1[p1] & 0b1111);
}

for(; p2 < version2.length() && version2[p2] != '.'; p2++){
v2 = (v2<<3) + (v2<<1) + (version2[p2] & 0b1111);
}
p1++; p2++;
if(v1 ^ v2)
return v1 > v2 ? 1 : -1;
}
return 0;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2021/01/30/PS/LeetCode/compare-version-numbers/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.