DevPath

← All problems

Evaluate Reverse Polish Notation

Medium stack · math

Description

Evaluate an arithmetic expression given in reverse Polish (postfix) notation. Operators are +, -, *, /. Division truncates toward zero.

Constraints

1 <= tokens <= 10000

Examples

Input: tokens = ["2","1","+","3","*"]

Output: 9

(2+1)*3

Hints (1)
  • Push numbers; on an operator, pop two and push the result.

Solutions

Operand stack. (requires "strconv") · Time O(n) · Space O(n)

func evalRPN(tokens []string) int {
    stack := []int{}
    for _, t := range tokens {
        switch t {
        case "+", "-", "*", "/":
            b := stack[len(stack)-1]
            a := stack[len(stack)-2]
            stack = stack[:len(stack)-2]
            switch t {
            case "+":
                stack = append(stack, a+b)
            case "-":
                stack = append(stack, a-b)
            case "*":
                stack = append(stack, a*b)
            case "/":
                stack = append(stack, a/b)
            }
        default:
            n, _ := strconv.Atoi(t)
            stack = append(stack, n)
        }
    }
    return stack[0]
}

Create a free account to submit solutions, track progress and save problems.

Create account