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
    1. while the next character is not digit
      1. do number = number*10 + currentDigit
    2.  push number to the stack.
  2. If the character is an operator, 
    1. pop operand from the stack, say it’s s1.
    2. pop operand from the stack, say it’s s2.
    3. 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.

Complete Code:

Output:

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

__________________________________________________
Top Companies Interview Questions..-

Google Microsoft Amazon Facebook more..

If you find anything incorrect or you feel that there is any better approach to solve the above problem, please write comment.
__________________________________________________

You may also like...

%d bloggers like this: