-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathevalRPN.go
More file actions
37 lines (31 loc) · 913 Bytes
/
Copy pathevalRPN.go
File metadata and controls
37 lines (31 loc) · 913 Bytes
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
/* https://leetcode.com/problems/evaluate-reverse-polish-notation/description/
Evaluate the value of an arithmetic expression in Reverse Polish Notation.
Valid operators are +, -, *, /. Each operand may be an integer or another expression.
Some examples:
["2", "1", "+", "3", "*"] -> ((2 + 1) * 3) -> 9
["4", "13", "5", "/", "+"] -> (4 + (13 / 5)) -> 6
*/
package lstack
import "strconv"
func evalRPN(tokens []string) int {
stack := []int{}
for _, token := range tokens {
if num, ok := strconv.Atoi(token); ok == nil {
stack = append(stack, num)
} else {
num1, num2 := stack[len(stack)-2], stack[len(stack)-1]
stack = stack[:len(stack)-2]
switch token {
case "+":
stack = append(stack, num1+num2)
case "-":
stack = append(stack, num1-num2)
case "*":
stack = append(stack, num1*num2)
case "/":
stack = append(stack, num1/num2)
}
}
}
return stack[0]
}