Challenge 6: Evaluate Postfix Expression Using a Stack

Try to compute "postfix" mathematical expressions using stacks!

Problem statement

The usual convention followed in mathematics is the infix expression. Operators like + and * appear between the two operands involved in the calculation:

6 + 3 * 8 - 4

Another convention is the postfix expression where the operators appear after the two operands involved in the expression. In postfix, the expression written above will be presented as:

6 3 8 * + 4 -

The two operands preceding an operator will be used with that operator.

  1. From the first block of digits 6 3 8, pick the last two, which are 3 and 8.
  2. Reading the operators from left to right, the first one is *. The expression now becomes 3 * 8
  3. The next number is 6 while the next operator is +. Now you have 6 + 8 * 3.
  4. The value of this expression is followed by 4, which is right before -. Consequently, you have 6 + 8 * 3 - 4.

In this problem, you have to implement the int evaluatePostFix(string exp) function, which will take a postfix expression given to it in a string. Your code should handle these four operators: +,-,*,/.

Input

With a string containing a valid postfix mathematical expression, each digit is considered a separate number, i.e., there are no double digit numbers.

Output

An integer result of the given postfix expression is the output.

Sample input

string exp = "921*-8-4+"; // 9 - 2 * 1 - 8 + 4

Sample output

3

Level up your interview prep. Join Educative to access 70+ hands-on prep courses.