-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbaseball-game.go
74 lines (65 loc) · 1.46 KB
/
baseball-game.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
package main
import (
"fmt"
"strconv"
)
// source: https://leetcode.com/problems/baseball-game/
func calPoints1(ops []string) int {
results := []int{}
res := 0
v := 0
for _, op := range ops {
num, err := strconv.ParseInt(op, 10, 32)
switch {
case err == nil:
v = int(num)
res += v
results = append(results, v)
case op == "C":
v = len(results) - 1
res -= results[v]
results = results[:v]
case op == "D":
v = results[len(results)-1] * 2
res += v
results = append(results, v)
case op == "+":
v = results[len(results)-1] + results[len(results)-2]
res += v
results = append(results, v)
}
}
return res
}
func calPoints(ops []string) int {
results := []int{}
for _, op := range ops {
switch op {
case "C":
results = results[:len(results)-1]
case "D":
results = append(results, results[len(results)-1]*2)
case "+":
results = append(results, results[len(results)-1]+results[len(results)-2])
default:
num, _ := strconv.ParseInt(op, 10, 32)
results = append(results, int(num))
}
}
res := 0
for _, v := range results {
res += v
}
return res
}
func main() {
// Example 1
var ops1 = []string{"5", "2", "C", "D", "+"}
fmt.Println("Expected: 30 Output: ", calPoints(ops1))
// Example 2
var ops2 = []string{"5", "-2", "4", "C", "D", "9", "+", "+"}
fmt.Println("Expected: 27 Output: ", calPoints(ops2))
// Example 3
var ops3 = []string{"1"}
fmt.Println("Expected: 1 Output: ", calPoints(ops3))
}