14724 - DS HW2 Arithmetic Evaluation   

Description

You are to write a C/C++ program that takes in arithmetic expressions and then evaluates the expressions.

 

Your program needs to support four operators: + (add), - (subtract), * (multiply), / (divide), as well as parentheses. The operators follow your common C arithmetic definition, including division gives the quotient and discards the remainder (e.g. `3/2` is 1). Note C allows negative divisors (e.g. `3/-2` is a valid expression and gives -1).

 

The expression will be in infix notation (e.g. `1+2`, `(5+3-2)/6`), without any spaces between the operators and operands.

 

As usual, you should compute the sub-expression within the parentheses first, multiply/division takes precedence over add/subtract, and that operators are left-associative (e.g. `5+3+2` is the same as `(5+3)+2`).

 

Note arguments for each operator can be a parenthesized sub-expression or any integer. In the case where the operand is a negative integer, it is denoted with a minus sign in the front of the integer (e.g. `(5+-3)+2` and `((5--3)+2)` is 4 and 10, respectively). For positive integers, their plus sign will always be omitted (e.g. `5-+3` and `5++3` will not occur).

 

It is possible the expression is invalid if the parentheses do not match (e.g. `(10+1)-5)/2`), in which case your program should output `bad expression`. You can otherwise assume the expression would be valid (e.g. cases such as `(1-2)7` will not occur).

 

You can assume that the operator arguments and intermediate results are always in the range `[4*10^9, -4*10^9]`, and can be stored in a `long` type variable. You can also assume that division by 0 will never occur.

 

Your program MAY use C++ standard library headers.

Input

A new line containing the number of arithmetic expressions to be evaluated (`M`), with the expressions starting on the next line, one expression per line.

`0 < M <= 10^5`

You can also assume that the sum of all expression lengths `l_sum <= 2 * 10^6`.

Output

The expression evaluation outcome, one outcome per line. Each outcome should be newline (`'\n'`) terminated.

Sample Input  Download

Sample Output  Download




Discuss