


You are given a string 'S' of length 'N' representing an arithmetic expression. Your task is to compute the result of the expression.
For Example:If the given arithmetic expression is: “2*3+5/6*3+15”, then the output will be 23.5.
Note:
1. The arithmetic expression consists of positive integers, +, -, *, and / (no parentheses).
2. The given input will always be a valid arithmetic expression.
3. There will be at least one integer in the given arithmetic equation.
The first line of the input contains an integer T denoting the number of test cases.
The first line of each test case contains one integer N, as described in the problem statement.
The second line of each test case contains one string of length N, representing a valid arithmetic expression.
Output Format:
For each test case, print a single line containing a single integer representing the result of the given arithmetic equation.
The output for each test case will be printed in a separate line.
Your answer will be considered correct if its absolute or relative error doesn’t exceed 10 ^ (-6).
Note:
You do not need to print anything. It has already been taken care of. Just implement the given function.
1 <= T <= 100
1 <= Length of the given string, N <= 30
It is guaranteed that the string will only be consisting of positive integers, +, -, * and / (no parentheses).
0 < positive integers <= 15
Time Limit: 1 sec.
1
7
2+3*6-7
13
The output is 13 since the equation will be evaluated as follows (2+3*6-7) → (2+18-7) → (20 - 7) → 13.
1
9
3*5+4/8-2
13.5
The output is 13.5 since the equation will be evaluated as follows (3*5+4/8-2) → (15+0.5 -2) → (15.5 - 2) → 13.5.
Can you think of a data structure that can help you evaluate the equation using the precedence of the operators?
In this approach, we will keep two different stacks, one for the operators and one for the operands. When we encounter any operand, we will push that into the operand stack.
If we encounter any operator, we will check if the current operator has precedence greater than the previous operator or not. If the current operator has precedence lower or equal to the previous operator, then we will calculate the result for the previous operator for its operand since its priority was higher. We continue the above process till we find an operator whose precedence is smaller than the precedence of the current operator. Finally, after the whole expression is parsed, we will evaluate the remaining operators left in the stack.
Steps:
O(N), where N is the length of the given string.
Since we are iterating the given string only once, the time complexity is O(N).
O(N), where N is the length of the given string.
Since we are storing each operator and operands using a stack, the space complexity will be O(N).