# 逆波兰表达式求值 python vs golang

## 题面

``````["20", "10", "+", "30", "*"] -> ((20 + 10) * 30) -> 900
["40", "130", "50", "/", "+"] -> (40 + (130 / 50)) -> 42``````

## 分析

• 遇到操作数入栈
• 碰到操作符取栈顶两操作数，计算结果入栈
• 注意出栈顺序，先进后出，尤其在计算除法与减法时

## python 解法

``````class Solution:
def evalRPN(self, tokens: List[str]) -> int:
st = []
for v in tokens:
if v in "+-*/":
b, a = st.pop(),st.pop()
if v == "+": st.append(a + b)
if v == "-": st.append(a - b)
if v == "*": st.append(a * b)
if v == "/": st.append(int(a / b))
else:
st.append(int(v))
return st[-1]``````

``````class Solution:
def evalRPN(self, tokens: List[str]) -> int:
st = []
for v in tokens:
if v in "+-*/":
b,a = st.pop(),st.pop()
st.append(eval("%d%s%d"%(a,v,b)))
else:
st.append(int(v))
return int(st[-1])``````

## golang实现

rune类型隐式转换字符串

``````import "strconv"
func evalRPN(tokens []string) int {
st := []int{}
for _,v := range tokens {
if v == "+" || v == "-" || v == "*" || v == "/" {
if len(st)< 2 {
return 0
}
b := st[len(st)-1]
st = st[:len(st)-1]
a := st[len(st)-1]
st = st[:len(st)-1]
switch v {
case "+": st = append(st, a+b)
case "-": st = append(st, a-b)
case "*": st = append(st, a*b)
case "/": st = append(st, a/b)
}
}else{
if num,err := strconv.Atoi(v); err == nil {
st = append(st, num)
}
}
}
return st[len(st)-1]
}``````

(=￣ω￣=)··· 暂无内容！

115

13

87

43