Be the first user to complete this post

  • 0
Add to List
Medium

406. Evaluation of Postfix Expressions (Polish Postfix notation) | Set 2

Earlier we had discussed how to evaluate postfix expressions where operands are of single-digit. In this article, we will discuss how to evaluate postfix expressions for any number ( not necessarily single digit.)

Postfix notation is a notation for writing arithmetic expressions in which the operands appear before their operators.

Let's assume the below

  • Operands are real numbers (could be multiple digits). 
  • Permitted operators: +,-, *, /, ^(exponentiation)
  • Blanks are used as a separator in expression.
  • Parenthesis are permitted

Example:

Postfix: 500 40+
Output: 540
Explanation: Infix expression of above postfix is:  500 + 40 which resolves to 540

Postfix: 20 50 3 6 + * * 300 / 2 -
Output: 28
Explanation: Infix expression of above postfix is:  20 * (50 *(3+6))/300-2 which resolves to 28

Approach: Use Stack

Algorithm:

Iterate through given expression, one character at a time

  1. If the character is a digit, initialize number = 0
    • while the next character is digit
      1. do number = number*10 + currentDigit
    •  push number to the stack.
  2. If the character is an operator, 
    • pop operand from the stack, say it's s1.
    • pop operand from the stack, say it's s2.
    • perform (s2 operator s1) and push it to stack.
  3. Once the expression iteration is completed, The stack will have the final result. pop from the stack and return the result.

Please see the walkthrough of an example below for more understanding.

Output:

Postfix Expression: 20 50 3 6 + * * 300 / 2 -
Evaluation: 28.0