Challenge: Evaluate Postfix Expressions Using Stacks
Let's try to compute postfix mathematical expressions using stacks!
We'll cover the following
Infix and Postfix Expressions #
In the infix expression (the usual convention followed in mathematics), operators like +
and *
appear between the operands involved in the calculation:
6 + 3 * 8 - 4
Another convention is the postfix expression, where the operators appear after the operands involved in the expression. In postfix, the expression written above will become:
6 3 8 * + 4 -
The two operands preceding an operator will be used with that operator
- From the first block of digits
6 3 8
, we pick the last two, which are3
and8
. - Reading the operators from left to right, the first one is
*
. The expression now becomes3 * 8
- The next number is
6
while the next operator is +, so we have6 + 8 * 3
. - The value of this expression is followed by
4
, which is right before-
. Hence we have6 + 8 * 3 - 4
.
Problem Statement #
In this problem, you have to implement the evaluatePostFix()
method that will compute a postfix expression given to it in a string.
Input #
The input is a string containing a valid postfix mathematic 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.
Sample Input #
expression = "921*-8-4+" # 9 - 2 * 1 - 8 + 4
Sample Output #
3
Explanation #
1st operation => 2 * 1 = 2,
2nd operation => 9 - 2 = 7,
3rd operation => 7 - 8 = -1,
4th operation => -1 + 4 = 3
Level up your interview prep. Join Educative to access 70+ hands-on prep courses.