A test bench logs circuit voltage adjustments as a postfix (Reverse Polish Notation) expression. Each token is either an arithmetic operator (+, -, *, /), given as a single standalone character, or an integer literal (which may be negative, e.g. -7; a negative literal always has more than one character, so it is never confused with the - operator token).
Evaluate the expression using the standard postfix rule: scan tokens left to right while maintaining a stack of values. Each operator pops its two most recently pushed values (the one popped second is the left-hand operand, the one popped first is the right-hand operand), applies itself, and pushes the result back. Division truncates toward zero (like integer division in C or Java), e.g. -7 / 2 evaluates to -3.
It is guaranteed that the tokens form a single valid, fully-reducible postfix expression, and that division by zero never occurs.
Line 1: an integer n, the number of tokens.
Line 2: n space-separated tokens.
A single integer: the value left on the stack after evaluating the whole expression.
Example 1
Input
3 3 4 +
Expected
7
Explanation
3 and 4 are pushed, then + pops them and pushes 3 + 4 = 7.
Example 2
Input
9 5 1 2 + 4 * + 3 -
Expected
14
Explanation
1+2=3, then 3*4=12, then 5+12=17, then 17-3=14.
Ready to solve this?
Sign in to open the editor, run your code against the sample tests, and submit against the full test suite.
Sign in to solve →