Skip to content

Latest commit

 

History

History
21 lines (21 loc) · 653 Bytes

150逆波兰表达式求值.md

File metadata and controls

21 lines (21 loc) · 653 Bytes
func evalRPN(tokens []string) int {
    stack := []int{}
    for _, token := range tokens {
        // 利用go的err特性代替判定是否为int
        if op, err := strconv.Atoi(token); err == nil {
            stack = append(stack, op)
        } else {
            x, y := stack[len(stack)-2], stack[len(stack)-1]
            stack = stack[:len(stack)-2]
            switch token {
            case "+": stack = append(stack, x + y)
            case "-": stack = append(stack, x - y)
            case "*": stack = append(stack, x * y)
            case "/": stack = append(stack, x / y)
            }
        }
    }
    return stack[0]
}