Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com

Evaluation of postfix expression

Easy
0/40
Average time to solve is 15m
profile
Contributed by
76 upvotes
Asked in companies
AmazonGoogleFacebook

Problem statement

An expression is called the postfix expression if the operator appears in the expression after the operands.

Example :

Infix expression: A + B  *  C - D 

Postfix expression:  A B + C D - *

Given a postfix expression, the task is to evaluate the expression. The answer could be very large, output your answer modulo (10^9+7). Also, use modular division when required.

Note:
1. Operators will only include the basic arithmetic operators like '*', '/', '+', and '-'.

2. The operand can contain multiple digits. 

3. The operators and operands will have space as a separator between them.

4. There won’t be any brackets in the postfix expression.
Detailed explanation ( Input/output format, Notes, Images )
Constraints
1 <= T <= 100
1 <= N <= 10^3
1 <= NUM <= 100

Where ‘N’ denotes the length of postfix expression and ‘NUM’ denotes the operand.

Time Limit: 1 sec
Sample input 1
2
2 3 1 * + 9 -
1 2 3 + * 8 -
Sample output 1
-4
-3
Explanation of sample input 1:
Test case 1:
2 3 1 * + 9 -

- : ( ) - ( )
9 : ( ) - (9)
+ : ( ( ) + ( ) ) - (9)
'*':  ( ( ) + ( ( ) * ( ) ) ) - (9)
1 : ( ( ) + ( ( ) * (1) ) ) - (9)
3 : ( ( ) + ( (3) * (1) ) ) - (9)
2 : ( (2) + ( (3) * (1) ) ) - (9) 

Result = (2 + 3) - 9 = 5 - 9 = -4

Test case 2:
1 2 3 + * 8 -

 - : ( ) - ( )
8 : ( ) - (8)
* : ( ( ) * ( ) ) - (8)
+ : ( ( ) * ( ( ) + ( ) ) ) - (8)
3 : ( ( ) * ( ( ) + (3) ) ) - (8)
2 : ( ( ) * ( (2) + (3) ) ) - (8)
1 : ( (1) * ( (2) + (3) ) ) - (8) 

Result = (1 * 5) - 8 = 5 - 8 = -3
Sample input 2
1
100 200 + 2 / 5 * 7 +
Sample output 2
757
Explanation of sample input 2:
100 + 200 = 300
300 / 2 = 150
150 * 5 = 750
750 + 7 = 757
Full screen
Console