150. 逆波兰表达式求值
根据逆波兰表示法,求表达式的值。
有效的运算符包括 +, -, *, / 。每个运算对象可以是整数,也可以是另一个逆波兰表达式。
说明:
整数除法只保留整数部分。
给定逆波兰表达式总是有效的。换句话说,表达式总会得出有效数值且不存在除数为 0 的情况。
package main
import (
"fmt"
"strconv"
)
func evalRPN(tokens []string) int {
stack :=make([]int,0)
for i:=0;i<len(tokens);i++{
if tokens[i]=="+" {
f :=stack[len(stack)-1]
s:= stack[len(stack)-2]
stack =stack[:len(stack)-2]
stack = append(stack,f+s)
}else if tokens[i]=="-" {
f :=stack[len(stack)-1]
s:= stack[len(stack)-2]
stack =stack[:len(stack)-2]
stack = append(stack,s-f)
}else if tokens[i]=="*" {
f :=stack[len(stack)-1]
s:= stack[len(stack)-2]
stack =stack[:len(stack)-2]
stack = append(stack,s*f)
}else if tokens[i]=="/" {
f :=stack[len(stack)-1]
s:= stack[len(stack)-2]
stack =stack[:len(stack)-2]
stack = append(stack,s/f)
}else {
s,_:= strconv.Atoi(tokens[i])
stack = append(stack,s)
}
}
return stack[0]
}
func main() {
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", "+"}))
}
精简版代码
func evalRPN(tokens []string) int {
number := []int{}
for _, val := range tokens{
l := len(number)
switch val {
case "+":
number = append(number[:l -2], number[l-2] + number[l-1])
case "-":
number = append(number[:l -2], number[l-2] - number[l-1])
case "*":
number = append(number[:l -2], number[l-2] * number[l-1])
case "/":
number = append(number[:l -2], number[l-2] / number[l-1])
default:
num, _ := strconv.Atoi(val)
number = append(number, num)
}
}
return number[0]
}