You are given a string ‘STR’, which represents an expression. Your task is to evaluate the value of the expression. The integer division should truncate toward zero.
For Example:Consider STR = “3+2*2”
Using the BODMAS rule, the expression after evaluation gives 7. Hence, the answer is 7.
The first line of input contains an integer ‘T’, denoting the number of test cases. Then each test case follows.
The first line of each test case contains a string ‘STR’, which represents the given expression.
Output Format:
For each test case, print a single integer representing the value of the given expression.
The output of each test case will be printed on a separate line.
Note:
You do not need to print anything. It has already been taken care of. Just implement the given function.
1 <= T <= 10
1 <= |STR| <= 10 ^ 6
‘STR’ consists of integers and operators (+, -, \, *).
‘STR’ represents a valid expression.
All the integers in the expression are non-negative integers in the range [0, 10 ^ 8].
Time Limit: 1 sec.
Note :
The evaluated string is always less than or equal to 10 ^ 9.
2
3+2*2
3+5/2
7
5
In the first test case, using the BODMAS rule, the expression after evaluation gives 7. Hence, the answer is 7.
In the second test case, using the BODMAS rule, the expression after evaluation gives 5. Hence, the answer is 5.
2
3/2
2+2/2
1
3
Can you solve it using a stack?
Scan the input string ’STR’ from left to right and evaluate the expressions based on the following rules:
The steps are as follows:
O(N), where ‘N’ is the length of the string.
We will iterate over the string ‘STR’ at most twice to evaluate the string. Hence the overall time complexity is O(N).
O(N), where ‘N’ is the length of the string.
In the worst case, the stack requires O(N) space complexity. Hence the overall space complexity is O(N).