There are many ways to represent arithmetic expressions.
We commonly use infix notation where operations are put in between values (i.e. ), but another less well-known method is prefix notation. This is where operations are put before values. For example, if we want to add two numbers we would write + x y
instead of x + y
. Furthermore, brackets are used to enforce order of evaluation.
The formal definition of prefix notation we will be using is as any one of the following options:
x
, wherex
is an integer.(+ x y)
, wherex
andy
are valid prefix notation expressions. The result of this expression is .
Your objective today is to evaluate prefix notation expressions that only involve addition.
Input Specification
The first and only line of input contains a valid prefix notation expression. You can expect the expression to only consist of the following characters: 0123456789()+-
(and the space:
)
Output Specification
The value of that expression.
Constraints
Any integer in the given expression will satisfy the following inequality: .
, where denotes the length of the prefix notation expression.
Sample Input
(+ 1 (+ (+ (+ 3 4) -2) 5))
Sample Output
11
Sample Explanation
Here is the sample input being simplified:
(+ 1 (+ (+ (+ 3 4) -2) 5))
(+ 1 (+ (+ 7 -2) 5))
(+ 1 (+ 5 5))
(+ 1 10)
(11)
11
Comments
I like how the title says its a recursion problem but literally none of the answers use recursion
I kept getting a WA on the second test case because the input was simply just an integer. Don't forget to add a test case for this.
If you got this problem in Brain****, I have respect for you.