forked from iostalks/Algorithms
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathevaluate_reverse_polish_notation.go
78 lines (65 loc) · 1.36 KB
/
evaluate_reverse_polish_notation.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
75
76
77
78
package main
import "fmt"
import "strconv"
type Stack struct {
nums []int
}
func (self *Stack) push(num int) {
self.nums = append(self.nums, num)
}
func (self *Stack) pop() int {
top := self.nums[len(self.nums)-1]
self.nums = self.nums[:len(self.nums)-1]
return top
}
func evalRPN(tokens []string) int {
if len(tokens) == 0 {
panic("no num, no operations")
}
operations := map[string]bool{
"+": true,
"-": true,
"*": true,
"/": true,
}
//handle one num case
if len(tokens) == 1 && operations[tokens[0]] == false {
result, err := strconv.Atoi(tokens[0])
if err == nil {
return result
}
}
stack := &Stack{}
result := 0
for _, token := range tokens {
if operations[token] {
result = calculate(token, stack.pop(), stack.pop())
stack.push(result)
} else {
num, err := strconv.Atoi(token)
if err == nil {
stack.push(num)
}
}
}
return result
}
func calculate(operation string, a int, b int) int {
switch operation {
case "+":
return b + a
case "-":
return b - a
case "*":
return b * a
case "/":
return b / a
}
panic("illegal oprator")
}
func main() {
fmt.Println(evalRPN([]string{"18"}))
fmt.Println(evalRPN([]string{"2", "1", "+", "3", "*"}))
fmt.Println(evalRPN([]string{"4", "13", "5", "/", "+"}))
fmt.Println(evalRPN([]string{"10", "6", "9", "3", "+", "-11", "*", "/", "*", "17", "+", "5", "+"}))
}