-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy path23_Compare_Version_Numbers.cpp
More file actions
74 lines (48 loc) · 1.89 KB
/
Copy path23_Compare_Version_Numbers.cpp
File metadata and controls
74 lines (48 loc) · 1.89 KB
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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
// 165. Compare Version Numbers
// Given two version strings, version1 and version2, compare them. A version string consists of revisions separated by dots '.'. The value of the revision is its integer conversion ignoring leading zeros.
// To compare version strings, compare their revision values in left-to-right order. If one of the version strings has fewer revisions, treat the missing revision values as 0.
// Return the following:
// If version1 < version2, return -1.
// If version1 > version2, return 1.
// Otherwise, return 0.
// Example 1:
// Input: version1 = "1.2", version2 = "1.10"
// Output: -1
// Explanation:
// version1's second revision is "2" and version2's second revision is "10": 2 < 10, so version1 < version2.
// Example 2:
// Input: version1 = "1.01", version2 = "1.001"
// Output: 0
// Explanation:
// Ignoring leading zeroes, both "01" and "001" represent the same integer "1".
// Example 3:
// Input: version1 = "1.0", version2 = "1.0.0.0"
// Output: 0
// Explanation:
// version1 has less revisions, which means every missing revision are treated as "0".
// Constraints:
// 1 <= version1.length, version2.length <= 500
// version1 and version2 only contain digits and '.'.
// version1 and version2 are valid version numbers.
// All the given revisions in version1 and version2 can be stored in a 32-bit integer.
class Solution
{
public:
int compareVersion(string version1, string version2)
{
stringstream s1(version1), s2(version2);
string token1, token2;
while (getline(s1, token1, '.') || getline(s2, token2, '.'))
{
int num1 = token1.empty() ? 0 : stoi(token1);
int num2 = token2.empty() ? 0 : stoi(token2);
if (num1 < num2)
return -1;
if (num1 > num2)
return 1;
token1.clear();
token2.clear();
}
return 0;
}
};