Problem:
Smart Calculator

Your task is to write a program which reads an expression and evaluates it.

The expression consists of numerical values, operators and parentheses, and the ends with '='.

The operators includes +, - , *, / where respectively represents, addition, subtraction, multiplication and division.

Precedence of the operators is based on usual laws. That is one should perform all multiplication and division first, then addition and subtraction. When two operators have the same precedence, they are applied from left to right.

You may assume that there is no division by zero.

All calculation is performed as integers, and after the decimal point should be truncated

Length of the expression will not exceed 100.

-1 × 109 ≤ intermediate results of computation ≤ 109

Input

The input is a sequence of datasets. The first line contains an integer n which represents the number of datasets. There will be n lines where each line contains an expression.

Output

For each datasets, prints the result of calculation.

Sample Input

2
4-2*3=
4*(8+4+3)=

Output for the Sample Input

-2
60

Solution in JAVA (judge verdict: Accepted)

import java.util.*;
import java.util.regex.*;

// (5-(6/2/2+50*3/2/3*6/4)/9*2-(6/2/2+50*3/2/3*6)-36)*2-1=

class Main{
	static Pattern addsub = Pattern.compile("^(.*?)(-?\\d+)([+Z])(-?\\d+)(.*)$");
	static Pattern muldiv = Pattern.compile("^(.*?)(-?\\d+)([*/])(-?\\d+)(.*)$");

	static String process(String s){
		//analyze parens
		int bidx=s.indexOf("(");
		while(bidx!=-1){
			int count=1,eidx=bidx+1;
			for(;count!=0;eidx++){
				if(s.charAt(eidx)=='(')count++;
				if(s.charAt(eidx)==')')count--;
			}
			s=s.substring(0,bidx)+process(s.substring(bidx+1,eidx-1))+s.substring(eidx);
			bidx=s.indexOf("(");
		}

		//calc without parens
		Matcher m=muldiv.matcher(s);
		while(m.find()){
			if(m.group(3).equals("*"))
				s=m.group(1)+(Integer.parseInt(m.group(2))*Integer.parseInt(m.group(4)))+m.group(5);
			else
				s=m.group(1)+(Integer.parseInt(m.group(2))/Integer.parseInt(m.group(4)))+m.group(5);
			m=muldiv.matcher(s);
		}

		m=addsub.matcher(s);
		while(m.find()){
			if(m.group(3).equals("+"))
				s=m.group(1)+(Integer.parseInt(m.group(2))+Integer.parseInt(m.group(4)))+m.group(5);
			else
				s=m.group(1)+(Integer.parseInt(m.group(2))-Integer.parseInt(m.group(4)))+m.group(5);
			m=addsub.matcher(s);
		}
		return s;
	}

	public static void main(String[]z){
		Scanner x=new Scanner(System.in);
		int n=x.nextInt();for(;n>0;n--){
			String s=x.next().replaceAll("-","Z");
			System.out.println(process(s.substring(0,s.length()-1)));
		}
	}
}