-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path165_Compare_Version_Numbers_(Medium).cpp
49 lines (44 loc) · 1.37 KB
/
165_Compare_Version_Numbers_(Medium).cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
class Solution {
public:
// I can't believe that this piece of code worked on the first try :)
int compareVersion(string version1, string version2) {
int ind1 = 0, ind2 = 0;
int size1 = version1.size();
int size2 = version2.size();
while(ind1 < size1 || ind2 < size2){
int v1 = 0, v2 = 0;
// Ignore leading zeroes (if any)
while(ind1 < size1 && version1[ind1] == '0'){
++ind1;
}
while(ind2 < size2 && version2[ind2] == '0'){
++ind2;
}
// Take all the binary digits (0 and 1) and consider them for an integer.
while(ind1 < size1 && version1[ind1] != '.'){
v1 *= 10;
v1 += version1[ind1] - '0';
++ind1;
}
while(ind2 < size2 && version2[ind2] != '.'){
v2 *= 10;
v2 += version2[ind2] - '0';
++ind2;
}
if(v1 < v2){
return -1;
}
else if(v1 > v2){
return 1;
}
// Ignore periods (if any)
if(ind1 < size1 && version1[ind1] == '.'){
++ind1;
}
if(ind2 < size2 && version2[ind2] == '.'){
++ind2;
}
}
return 0;
}
};