Back
Close

Reverse Polish Notation

Statement

 Goal

You have to correctly interpret RPN (Reverse Polish Notation) instructions and print the stack when the instruction line has been read (from left to right).
If the instruction is a number, simply put in on top of the stack (on the right).
The operations (ADD, SUB, MUL, DIV, MOD) pop the last two numbers out of the stack and push back on top the result. You can safely assume that the numbers are all integers.
For example after, 2 5 SUB 8, the stack is -3 8.
DIV is the integer quotient and MOD the remainder of the division.
There are also operators that act on the stack itself:
POP removes the top number.
DUP duplicates the top number.
SWP swaps the two top numbers. 4 5 SWP 6 swaps 4 and 5 then pushes 6 on top, the stack is 5 4 6.
3 ROL pops the top number (here it’s 3) then brings to the top the third number of the stack. For example, if the stack is 1 2 3 4, 3 ROL changes it in 1 3 4 2.
Input
The first line is the number of instructions on the second line.
The last line is the instructions line.

6
2 4 ADD 5 MUL -4
Output
You must print the stack, the top on the right.
If an instruction has fewer operands than needed or if we try to divide by 0, stop everything and print ERROR after the current stack. The popped values before the crash are still popped. For example if the stack is 1 2 3 0 and we try MOD, the stack will be 1 2 and you have to print 1 2 ERROR.

30 -4
Constraints
0 < N < 100
Example
Input
3
1 3 ADD
Output
4

Tags
Reverse Polish NotationStackInterpreters

Difficulty
Medium

Test cases
Simple operation Test
Input
3 1 3 ADD
Output
4

Validator 1 Validator
Input
4 2 40 ADD 12
Output
42 12

More operations Test
Input
6 2 4 ADD 5 MUL -4
Output
30 -4

Validator 2 Validator
Input
9 -3 6 5 MUL ADD 6 SUB 3 DIV
Output
7

Playing with the stack Test
Input
5 2 5 7 6 SWP
Output
2 5 6 7

Validator 3 Validator
Input
9 -4 7 10 6 3 ROL 4 SWP DUP
Output
-4 10 6 4 7 7

Stack underflow Test
Input
2 4 ADD
Output
ERROR

Stack underflow Validator
Input
2 1 SUB
Output
ERROR

ROL Test
Input
6 1 2 3 4 3 ROL
Output
1 3 4 2

ROL Validator
Input
6 1 2 3 4 3 ROL
Output
1 3 4 2

Divide by zero Test
Input
3 1 0 DIV
Output
ERROR

Divide by zero Validator
Input
3 1 0 DIV
Output
ERROR

Error In Progress Test
Input
4 1 1 0 DIV
Output
1 ERROR

Error In Progress Validator
Input
6 5 1 0 8 MUL DIV
Output
5 ERROR

Solution language

Solution

Stub generator input