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
.
character.The
.
character does not represent a decimal point and is used to separate number sequences.
Hide Tags
Analysis:
The problem itself is straightforward and simple. But when start to code, you will find there are lots of trivial things need to pay attention. Following is an example:
The first thing is how to fetch the values between the interval of '.', while note that the two strings are with different sections and with different length for each section. In such a case, the outermost loop should be 'while' loop instead of 'for' loop. The inner loop can use both.
The second thing is how to compare two strings with different length. One method is to transfer them into int and compare. Another convenient way is to compare two strings directly when they are with the same length!
string a="123", b="012";
bool c=a>b; // we get true
if they are not with the same length, insert '0' on the left side to make them have the same length and them compare directly.
/////////////////////////////////////////////////////////////////////////////////////////////////////
//code
class Solution {
public:
int compareVersion(string version1, string version2) {
int i = 0, j = 0;
while (i!=version1.size() || j!=version2.size()){
string t1 = { "0" }, t2 =
{ "0" };
for (; i < version1.size(); i++){
if (version1[i] != '.'){
t1.push_back(version1[i]);
}
else {
i++; break;
}
}
for (; j < version2.size(); j++){
if (version2[j] != '.'){
t2.push_back(version2[j]);
}
else {
j++; break;
}
}
//make two strings with equal length
if (t1.size() >
t2.size())t2.insert(t2.begin(), t1.size() - t2.size(), '0');
else if (t1.size() <
t2.size())t1.insert(t1.begin(), t2.size() - t1.size(), '0');
else{};
//compare
if (t1 > t2)return 1;
else if (t1 < t2)return -1;
else {
//if (i == version1.size() - 1 && j ==
version2.size() - 1)return 0;
}
}
return 0;
}
};
No comments:
Post a Comment