Compare Version Numbers (Easy)

Description:

Compare two version numbers version1 and version2.
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 . 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.

Analysis

比较数的大小,将字符串进行分割后一一比较就好了~

My Solution

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
//C++
class Solution {

private:
vector<int> splite(string s){
vector<int> ans;
ans.clear();
char c[100];
int i , j;
for(i=0,j=0;i<(int)s.length();i++){
if(s[i]!='.')
c[j++]=s[i];
else{
c[j]=0;
ans.push_back(atoi(c));
j = 0;
}
}
if(j!=0){
c[j]=0;
ans.push_back(atoi(c));
}
return ans;
}

public:
int compareVersion(string version1, string version2) {
vector<int> v1,v2;
v1 = this->splite(version1);
v2 = this->splite(version2);
int len1 = v1.size();
int len2 = v2.size();
int len = min(len1,len2);
for(int i=0;i<len;i++){
if(v1[i]>v2[i])
return 1;
if(v1[i]<v2[i])
return -1;
}
for(int i=len;i<len1;i++)
if(v1[i]!=0)
return 1;
for(int i=len;i<len2;i++)
if(v2[i]!=0)
return -1;
return 0;
}
};