Compare two version numbers version1 and version2.
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Solution { | |
public: | |
int compareVersion(string v1, string v2) { | |
if(v1.empty()&&v2.empty()) | |
return 0; | |
string s1; | |
int i1; | |
int p1=0; | |
while(v1[p1]!='.'&&p1<v1.length()) | |
s1=s1+string(1, v1[p1++]); | |
p1=p1<v1.length()? p1+1:p1; | |
i1=s1.empty()? 0:stoi(s1); | |
string s2; | |
int i2; | |
int p2=0; | |
while(v2[p2]!='.'&&p2<v2.length()) | |
s2=s2+string(1, v2[p2++]); | |
p2=p2<v2.length()? p2+1:p2; | |
i2=s2.empty()? 0:stoi(s2); | |
if(i1==i2){ | |
return compareVersion(v1.substr(p1, v1.length()-p1), v2.substr(p2, v2.length()-p2)); | |
} | |
if(i1>i2) | |
return 1; | |
if(i1<i2) | |
return -1; | |
} | |
}; |
Round 2 solution:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Solution { | |
public: | |
int compareVersion(string version1, string version2) { | |
int p1=0, p2=0; | |
while(p1<version1.length()||p2<version2.length()){ | |
string d1, d2; | |
while(version1[p1]!='.'&&p1<version1.length()) | |
d1=d1+version1[p1++]; | |
while(version2[p2]!='.'&&p2<version2.length()) | |
d2=d2+version2[p2++]; | |
int n1=d1.empty()? 0:stoi(d1); | |
int n2=d2.empty()? 0:stoi(d2); | |
if(n1>n2) return 1; | |
if(n2>n1) return -1; | |
p1++; p2++; | |
} | |
return 0; | |
} | |
}; |
No comments:
Post a Comment