Skip to content

Commit 7f76e24

Browse files
committed
add code for 165. Compare Version Numbers
1 parent 468727c commit 7f76e24

File tree

1 file changed

+47
-0
lines changed

1 file changed

+47
-0
lines changed

leetcode/cpp/string/165.cpp

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
class Solution {
2+
public:
3+
int compareVersion(string v1, string v2) {
4+
int i1=0,i2=0;
5+
while(i1<v1.length() && i2<v2.length()) {
6+
int n1=-1, n2=-1;
7+
8+
int p1 = (int)v1.find('.', i1);
9+
if (p1!=string::npos) {
10+
n1 = stoi(v1.substr(i1, p1-i1));
11+
i1 = p1+1;
12+
}
13+
else {
14+
n1 = stoi(v1.substr(i1));
15+
i1 = v1.length();
16+
}
17+
18+
int p2 = (int)v2.find('.', i2);
19+
if (p2!=string::npos) {
20+
n2 = stoi(v2.substr(i2, p2-i2));
21+
i2 = p2+1;
22+
}
23+
else {
24+
n2 = stoi(v2.substr(i2));
25+
i2 = v2.length();
26+
}
27+
28+
if (n1!= -1 && n2!= -1) {
29+
if (n1>n2) return 1;
30+
else if (n1<n2) return -1;
31+
}
32+
}
33+
if (i1 == v1.length()) {
34+
for(; i2<v2.length(); i2++) {
35+
if (v2[i2] != '.' && v2[i2] != '0')
36+
return -1;
37+
}
38+
} else if (i2 == v2.length()) {
39+
for(; i1<v1.length(); i1++) {
40+
if (v1[i1] != '.' && v1[i1] != '0')
41+
return 1;
42+
}
43+
}
44+
return 0;
45+
46+
}
47+
};

0 commit comments

Comments
 (0)