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
在做这个题目之前,我们先了解一下什么是逆波兰式?
我们平常人类常用的计算方式(1+2)*(3+4)-(5*6)是中缀表达式,这种表达式对我们来说很简单,但是对计算机来说却很复杂。
所以转化成计算机喜欢的逆波兰式,上面的例子转化为逆波兰式则为
->"(1+2)*(3+4)","(5*6)","-"
->"(1+2)","(3+4)","*","5","6","*","-"
->"1","2","+","3","4","+","*","5","6","*","-"
这种算式需要采用栈式结构进行计算,先进后出。
package main
import (
"fmt"
"strconv"
)
/**
*
* @param tokens string字符串一维数组
* @return int整型
*/
type Stack struct {
i int
numList []int
}
func (stack *Stack) Push(num int) {
stack.numList = append(stack.numList, num)
stack.i++
}
func (stack *Stack) Pop() (num int) {
num = stack.numList[stack.i-1]
stack.numList = stack.numList[0 : stack.i-1]
stack.i--
return
}
func main() {
var tokens = []string{"2", "1", "+", "3", "*"}
res := evalRPN(tokens)
fmt.Println(res)
}
func evalRPN(tokens []string) int {
// write code here
stack := new(Stack)
for _, str := range tokens {
if str == "+" || str == "-" || str == "*" || str == "/" {
num1 := stack.Pop()
num2 := stack.Pop()
var res int
switch str {
case "+":
res = num2 + num1
break
case "-":
res = num2 - num1
break
case "*":
res = num2 * num1
break
case "/":
res = num2 / num1
break
}
stack.Push(res)
fmt.Println("ha", stack)
} else {
intNum, _ := strconv.Atoi(str)
stack.Push(intNum)
fmt.Println("hei", stack)
}
}
return stack.Pop()
}