150.逆波兰表达式求值
150.逆波兰表达式求值
题解
逆波兰表达式是一种后缀表达式,遇到运算符就弹出两个进行运算即可,大水题
代码
package main
import "strconv"
func evalRPN(tokens []string) int {
if len(tokens) == 0 {
return 0
}
stack := make([]int, 0, len(tokens))
for i := 0; i < len(tokens); i++ {
val := tokens[i]
switch val {
case "+", "-", "*", "/":
a2 := stack[len(stack)-1]
stack = stack[:len(stack)-1]
a1 := stack[len(stack)-1]
stack = stack[:len(stack)-1]
result := 0
switch val {
case "+":
result = a1 + a2
case "-":
result = a1 - a2
case "*":
result = a1 * a2
case "/":
result = a1 / a2
}
stack = append(stack, result)
default:
v, _ := strconv.Atoi(val)
stack = append(stack, v)
}
}
return stack[0]
}
func main() {
}
|