/
split.go
71 lines (61 loc) · 1.33 KB
/
split.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
package solution
// you can also use imports, for example:
import (
"errors"
"fmt"
"strconv"
)
// you can use fmt.Println for debugging purposes, e.g.
// fmt.Println("this is a debug message")
func Solution(expression string) int {
// write your code in Go 1.4
stack := Stack{}
fmt.Println(expression)
for _, element := range expression {
value, err := strconv.Atoi(string(element))
if err != nil {
operand1, err := stack.Pop()
if err != nil {
return -1
}
operand2, err := stack.Pop()
if err != nil {
return -1
}
operation := strconv.QuoteRuneToASCII(element)
if operation == "'+'" {
total := operand1 + operand2
stack.Push(total)
} else if operation == "'*'" {
total := operand1 * operand2
stack.Push(total)
} else {
return -1
}
} else {
stack.Push(value)
}
}
finalValue, err := stack.Pop()
if err != nil {
return -1
} else {
return finalValue
}
}
type Stack []int
func (s *Stack) Push(value int) {
//fmt.Println(value)
*s = append(*s, value)
}
func (s *Stack) Pop() (int, error) {
if s.IsEmpty() {
return 0, errors.New("Can't pop from an empty stack.")
}
ret := (*s)[len(*s)-1]
*s = (*s)[0 : len(*s)-1]
return ret, nil
}
func (s *Stack) IsEmpty() bool {
return len(*s) == 0
}