Compare two version numbers version1 and version1.
If version1 > version2 return 1, if version1 < version2 return -1, otherwise return 0.
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
The
For instance,
.
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
https://oj.leetcode.com/problems/compare-version-numbers/
python --
class Solution:
# @param version1, a string
# @param version2, a string
# @return an integer
def compareVersion(self, version1, version2):
vlong = version1.split('.')
vshort = version2.split('.')
swapflag = 1
if len(vlong) < len(vshort):
swapflag = -1
vlong, vshort = vshort, vlong
for index in range(0, len(vlong)):
v1 = float(vlong[index])
v2 = float(vshort[index]) if (index < len(vshort)) else 0
if (v1 > v2):
return 1 * swapflag
elif (v1 < v2):
return -1 * swapflag
return 0
C++
class Solution {
public:
int compareVersion(string version1, string version2) {
unsigned int p1 = 0;
unsigned int p1pre = 0;
unsigned int p2 = 0;
unsigned int p2pre = 0;
while(p1 < version1.size() && p2 < version2.size()) {
string v1 = "";
string v2 = "";
for (p1 = p1pre; p1 < version1.size(); ++p1){
if (version1[p1] == '.') break;
v1.push_back(version1[p1]);
}
for (p2 = p2pre; p2 < version2.size(); ++p2){
if (version2[p2] == '.') break;
v2.push_back(version2[p2]);
}
int n1 = stoi(v1);
int n2 = stoi(v2);
if (n1 > n2) return 1;
if (n1 < n2) return -1;
p1pre = p1 + 1;
p2pre = p2 + 1;
}
if (p2 >= version2.size()) {
for(unsigned int ii = p1pre; ii < version1.size(); ++ii) {
if (version1[ii] != '0' && version1[ii] != '.') return 1;
}
}
else if (p1 >= version1.size()) {
for(unsigned int ii = p2pre; ii < version2.size(); ++ii) {
if (version2[ii] != '0' && version2[ii] != '.') return -1;
}
}
return 0;
}
};
No comments:
Post a Comment