后缀表达式 四则运算

 

 

https://leetcode.cn/problems/8Zf90G/

 

func evalRPN(tokens []string) int {
    stack := make([]int,0)
    for _, token := range tokens {
        val, err := strconv.Atoi(token)
        if err == nil {
            stack = append(stack, val)
        } else {
            //num2和num1的顺序不能搞反
            num2:= stack[len(stack)-1]
            stack = stack[:len(stack)-1]
            num1:= stack[len(stack)-1]
            stack = stack[:len(stack)-1]
            switch token {
            case "+":
                stack = append(stack, num1+num2)
            case "-":
                stack = append(stack, num1-num2)
            case "*":
                stack = append(stack, num1*num2)
            default:
                stack = append(stack, num1/num2)
            }
        }
    }
    return stack[0]
}

 

posted @ 2022-07-06 20:11  知道了呀~  阅读(71)  评论(0编辑  收藏  举报