Skip to content

Commit 5b9303d

Browse files
author
Openset
committed
Add: compare_version_numbers
1 parent e2a88a6 commit 5b9303d

File tree

2 files changed

+98
-0
lines changed

2 files changed

+98
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -1 +1,34 @@
11
package compare_version_numbers
2+
3+
import (
4+
"strconv"
5+
"strings"
6+
)
7+
8+
func compareVersion(version1 string, version2 string) int {
9+
v1s := strings.Split(version1, ".")
10+
v2s := strings.Split(version2, ".")
11+
i, l1 := 0, len(v1s)
12+
j, l2 := 0, len(v2s)
13+
for i < l1 || j < l2 {
14+
v1, v2 := "0", "0"
15+
if i < l1 {
16+
v1 = v1s[i]
17+
i++
18+
}
19+
if j < l2 {
20+
v2 = v2s[j]
21+
j++
22+
}
23+
n1, _ := strconv.Atoi(v1)
24+
n2, _ := strconv.Atoi(v2)
25+
if n1 != n2 {
26+
if n1 < n2 {
27+
return -1
28+
} else {
29+
return 1
30+
}
31+
}
32+
}
33+
return 0
34+
}
Original file line numberDiff line numberDiff line change
@@ -1 +1,66 @@
11
package compare_version_numbers
2+
3+
import "testing"
4+
5+
type caseType struct {
6+
v1 string
7+
v2 string
8+
expected int
9+
}
10+
11+
func TestCompareVersion(t *testing.T) {
12+
tests := [...]caseType{
13+
{
14+
v1: "1.0.01",
15+
v2: "1.00.1",
16+
expected: 0,
17+
},
18+
{
19+
v1: "1.0.0",
20+
v2: "1",
21+
expected: 0,
22+
},
23+
{
24+
v1: "0.1",
25+
v2: "1.1",
26+
expected: -1,
27+
},
28+
{
29+
v1: "7.5.2.4",
30+
v2: "7.5.3",
31+
expected: -1,
32+
},
33+
34+
{
35+
v1: "7.00",
36+
v2: "7.001",
37+
expected: -1,
38+
},
39+
{
40+
v1: "1.1",
41+
v2: "1.10",
42+
expected: -1,
43+
},
44+
{
45+
v1: "1.0.1",
46+
v2: "1",
47+
expected: 1,
48+
},
49+
{
50+
v1: "1.10",
51+
v2: "1.2",
52+
expected: 1,
53+
},
54+
{
55+
v1: "1.10.05",
56+
v2: "1.9.10",
57+
expected: 1,
58+
},
59+
}
60+
for _, tc := range tests {
61+
output := compareVersion(tc.v1, tc.v2)
62+
if output != tc.expected {
63+
t.Fatalf("input: %v %v, output: %v, expected: %v", tc.v1, tc.v2, output, tc.expected)
64+
}
65+
}
66+
}

0 commit comments

Comments
 (0)