Be the first user to complete this post

  • 0
Add to List
Medium

416. Evaluation of Prefix Expressions (Polish Notation) | Set 2

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

Prefix notation is a notation for writing arithmetic expressions in which the operands appear after 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 the above prefix is:  500 + 40 which resolves to 540

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

Approach: Use Stack

Algorithm:

Reverse the given expression and Iterate through it, one character at a time

  1. If the character is a digit, initialize String temp;
    • while the next character is not a digit
      • do temp = temp + currentDigit
    • convert Reverse temp into Number.
    •  push Number to the stack.
  2. If the character is an operator, 
    • pop the operand from the stack, say it's s1.
    • pop the operand from the stack, say it's s2.
    • perform (s1 operator s2) 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:

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