Evaluate a Postfix Expression
Problem statement
Evaluate a valid arithmetic expression written in postfix notation. The input is an array of tokens read from left to right. An integer token contributes a value; an operator consumes the two most recent values. The earlier value is the left operand and the later value is the right operand.
The binary operators are +, -, *, and /. Division truncates toward zero. Return the final integer value.
Function
evaluatePostfix(tokens: String[]) → intExamples
Example 1
tokens = ["2","3","+","4","*"]return = 20Add 2 and 3, then multiply the sum by 4.
Example 2
tokens = ["7","-3","/"]return = -2Seven divided by negative three truncates toward zero.
Example 3
tokens = ["5","1","2","+","4","*","+","3","-"]return = 14The expression is 5 + (1 + 2) * 4 - 3.
Constraints
1 <= tokens.length <= 10000.- Each token is a signed integer in
[-200, 200]or one of+,-,*, and/. - The tokens form a valid postfix expression, and no division has a zero divisor.
- Every intermediate result fits in a signed 32-bit integer.