-
Notifications
You must be signed in to change notification settings - Fork 0
/
0165.go
74 lines (66 loc) · 2.2 KB
/
0165.go
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
// Source: https://leetcode.com/problems/compare-version-numbers
// Title: Compare Version Numbers
// Difficulty: Medium
// Author: Mu Yang <http://muyang.pro>
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// 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.
//
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
package main
import (
"strconv"
"strings"
)
func compareVersion(version1 string, version2 string) int {
ver1 := strings.Split(version1, ".")
ver2 := strings.Split(version2, ".")
l1, l2 := len(ver1), len(ver2)
n := max(l1, l2)
for i := 0; i < n; i++ {
v1, v2 := 0, 0
if i < l1 {
v1, _ = strconv.Atoi(ver1[i])
}
if i < l2 {
v2, _ = strconv.Atoi(ver2[i])
}
if v1 < v2 {
return -1
}
if v1 > v2 {
return 1
}
}
return 0
}