Question: Postfix expression evaluation
A string containing the postfix expression is given to you. Evaluate it and print the single integer giving the answer.
Input Description:
The first line of the input is a string N, containing operators and numbers separated by a single space which forms a postfix expression.
Output Description:
Evaluate the post expression and print the result.
Sample Input:
5 3 1 * + 9 -
Sample Output:
-1
Answer:
Steps to evaluate a prefix expression:
- Split the prefix expression based on space (" ") or blank string ("") as per the given input.
- Store the split characters in an array.
- Create an evaluation array with no elements (blank array).
- Iterate through the elements of the characters array.
- If the character is a number, simply push the character into the evaluation array.
- if the character is an operator (+, -, *, /, %), then pop 2 elements from the evaluation array. Store the first popped number as the right Operand and the second as the left Operand.
- Calculate the result using the operands and current operator. [left operand (operator) right operand]. You may use switch-case or if-else statements to recognize the operator.
- After calculating the result push the result into the evaluation array.
- After iterating through all the elements of the characters array, the evaluation Array will have only one number, resulting from the evaluation of the prefix expression.
- Pop the element and return it as the output.
Comments
Post a Comment