#C11209. Evaluate Reverse Polish Notation (RPN) Expression
Evaluate Reverse Polish Notation (RPN) Expression
Evaluate Reverse Polish Notation (RPN) Expression
You are given a mathematical expression written in Reverse Polish Notation (RPN). In RPN, every operator follows all of its operands. For example, the expression 2 1 + 3 *
is interpreted as (2 + 1) * 3 which evaluates to 9.
The allowed operators are: +
, -
, *
, and /
. When performing division, use integer division that truncates toward zero. The input expression is a single string where tokens (operands or operators) are separated by a single whitespace.
The evaluation can be formally described using a stack. For each token:
- If the token is an operand, push it onto the stack.
- If the token is an operator, pop the top two elements from the stack, and apply the operator. Push the result back onto the stack.
The final answer is the only element remaining on the stack after the entire expression has been processed.
In mathematical notation, for an operator op and operands a and b, the operation is computed as:
\[ result = a \; op \; b \]
inputFormat
The input is provided via stdin as a single line string representing the RPN expression. Tokens are separated by a single space.
For example:
2 1 + 3 *
outputFormat
The output should be printed to stdout as an integer representing the evaluation result of the RPN expression.
For example:
9## sample
2 1 + 3 *
9