-
Notifications
You must be signed in to change notification settings - Fork 17
Expand file tree
/
Copy pathevaluate-reverse-polish-notation.go
More file actions
48 lines (37 loc) · 1.04 KB
/
evaluate-reverse-polish-notation.go
File metadata and controls
48 lines (37 loc) · 1.04 KB
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
package main
import "strconv"
func evalRPN(tokens []string) int {
stack := []string{}
for _, token := range tokens {
left, right := "", ""
if len(stack) >= 2 {
left, right = stack[len(stack)-2], stack[len(stack)-1]
}
switch token {
case "+":
leftInt, _ := strconv.Atoi(left)
rightInt, _ := strconv.Atoi(right)
stack = stack[:len(stack)-2]
stack = append(stack, strconv.Itoa(leftInt+rightInt))
case "-":
leftInt, _ := strconv.Atoi(left)
rightInt, _ := strconv.Atoi(right)
stack = stack[:len(stack)-2]
stack = append(stack, strconv.Itoa(leftInt-rightInt))
case "/":
leftInt, _ := strconv.Atoi(left)
rightInt, _ := strconv.Atoi(right)
stack = stack[:len(stack)-2]
stack = append(stack, strconv.Itoa(leftInt/rightInt))
case "*":
leftInt, _ := strconv.Atoi(left)
rightInt, _ := strconv.Atoi(right)
stack = stack[:len(stack)-2]
stack = append(stack, strconv.Itoa(leftInt*rightInt))
default:
stack = append(stack, token)
}
}
result, _ := strconv.Atoi(stack[0])
return result
}