Problem Description
小明在你的帮助下,破译了Ferrari设的密码门,正要往前走,突然又出现了一个密码门,门上有一个算式,其中只有“(”、“)”、“0-9”、“+”、“-”、“*”、“/”、“^”,求出的值就是密码。小明的数学学得不好,还需你帮他的忙。(“/”用整数除法)
Input
输入的第一行为T,表示测试示例的个数,每组数据只有一行是一个算式(算式长度<=30)。
Output
对于每组数据,输出算式的值(所有数据在2^31-1内)。
Sample Input
1 1+(3+2)*(7^2+6*9)/(2)
Sample Output
258
#include<cstdio>
#include<stack>
using namespace std;
char str[100];
int yx(char c)
{
if(c == '+' || c == '-') return 1;
if(c == '*' || c == '/') return 2;
if(c == '^') return 3;
if(c == '(') return 0;
}
void compute(stack<int> &s1, stack<char> &s2)
{
int x, y, ans;
char c;
y = s1.top();
s1.pop();
x = s1.top();
s1.pop();
c = s2.top();
s2.pop();
if(c == '+') ans = x + y;
if(c == '-') ans = x - y;
if(c == '*') ans = x * y;
if(c == '/') ans = x / y;
if(c == '^')
{
int i, a = 1;
for(i = 0; i < y; i++) a = a * x;
ans = a;
}
s1.push(ans);
}
int main()
{
int T;
scanf("%d", &T);
getchar();
while(T--)
{
int i, num = 0, flag = 0;
stack<int> s_int;
stack<char> s_char;
gets(str);
for(i = 0; str[i] != '\0'; i++)
{
if(str[i] >= '0' && str[i] <= '9')
{
num = num * 10 + str[i] - '0';
flag = 1;
}
else
{
if(flag)
{
s_int.push(num);
num = 0;
flag = 0;
}
//如果是左括号直接入符号栈
if(str[i] == '(')
{
s_char.push('(');
continue;
}
//把到最近一个左括号中间的结果全算出来
if(str[i] == ')')
{
//没有到左括号继续 运算
while(s_char.top() != '(') compute(s_int, s_char);
//将左括号出符号栈
s_char.pop();
continue;
}
/ / 如果输入的不是左右括号,而是算符
//如果符号栈为空,直接将算符入 栈
if(s_char.empty()) s_char.push(str[i]);
else
{
//如果符号栈不为空,且栈顶算符的优先级大于当前算符,则计算栈顶算符的相关运算
while(!s_char.empty() && yx(s_char.top()) >= yx(str[i]) compute(s_int, s_char);
//计算完后,将当前算 符入栈
s_char.push(str[i]);
}
}
}
//算出剩下两个栈中的结果
//如果最后是数字,将数字入栈。
if(flag)
{
s_int.push(num);
num = 0;
flag = 0;
}
//如果算符栈不为空,一直计算下去
while(!s_char.empty()) compute(s_int, s_char);
printf("%d\n", s_int.top());
s_int.pop();
}
return 0;
}