-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathevaluate-reverse-polish-notation.go
65 lines (54 loc) · 1.13 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
package main
import (
"fmt"
"strconv"
)
// source: https://leetcode.com/problems/evaluate-reverse-polish-notation/
func evalRPN(tokens []string) int {
stack := make([]string, 0)
push := func(x string) {
stack = append(stack, x)
}
pop := func() string {
n := len(stack)
x := stack[n-1]
stack = stack[:n-1]
return x
}
for _, t := range tokens {
push(t)
}
var evaluate func() int
evaluate = func() int {
x := pop()
if v, err := strconv.ParseInt(x, 10, 64); err == nil {
return int(v)
}
r := evaluate()
l := evaluate()
switch x {
case "+":
return l + r
case "-":
return l - r
case "*":
return l * r
case "/":
return l / r
default:
return -1
}
}
return evaluate()
}
func main() {
// Example 1
var tokens1 = []string{"2", "1", "+", "3", "*"}
fmt.Println("Expected: 9 Output: ", evalRPN(tokens1))
// Example 2
var tokens2 = []string{"4", "13", "5", "/", "+"}
fmt.Println("Expected: 6 Output: ", evalRPN(tokens2))
// Example 3
var tokens3 = []string{"10", "6", "9", "3", "+", "-11", "*", "/", "*", "17", "+", "5", "+"}
fmt.Println("Expected: 22 Output: ", evalRPN(tokens3))
}