表达式计算 | ||
---|---|---|
Time Limit: 1000 MS | Memory Limit: 1000 KB |
Description
输入一串表达式,计算其结果。表达式包括数字'0'~'9'、'+'、'-'、'*'、'/'、'('、')',并以符号'#'结尾。
在计算中,除法以向下取整计算。
保证表达式合法,且结果不超过long long范围。
Input
输入的第一行是一个int型整数T,表示一个有T组数据。
接下来T行,每行一个一个表达式。
Output
输出T行,每行一个整数,表示求得的结果。
Sample Input
2
1-2#
3*(1+2)#
Sample Output
-1
9
代码结果:
#include<iostream>
#include<stack>
using namespace std;
stack<char>aba;
stack<long long>fpx;
int prio(char a)
{
if (a == ')')return 0;
else if (a == '+' || a == '-')return 1;
else if (a == '*' || a == '/')return 2;
else if (a == '(')return 3;
else return -1;
}
int in_prio(char a)
{
if (a == '+' || a == '-')return 1;
else if (a == '*' || a == '/')return 2;
else if (a == '(')return 0;
else return -1;
}
void computing(char n)
{
long long a = fpx.top();
fpx.pop();
long long b = fpx.top();
fpx.pop();
if (n == '+') fpx.push(a + b);
else if (n == '-')fpx.push(b - a);
if (n == '*')fpx.push(a * b);
else if (n == '/' )fpx.push( b / a);
}
int main()
{
int T = 0;
cin >> T;
for (int t = 0; t < T; t++)
{
char ch[1000];
cin >> ch;
bool flag = false;
int i = 0;
long long x = 0;
while (ch[i]!= '#')
{
if ( '0' <=ch[i]&& ch[i] <='9')
{
x = x * 10 + int(ch[i] - '0');
flag = true;
}
else if (flag)
{
flag = false;
fpx.push(x);
x = 0;
}
if (ch[i] == ')')
{
while( aba.top() != '(' )
{
computing(aba.top());
aba.pop();
}
aba.pop();
}
if(ch[i] == '(')aba.push(ch[i]);
if(ch[i]=='+'||ch[i]=='-'||ch[i]== '*' || ch[i] == '/')
{
if (!aba.empty())
{
while (in_prio(aba.top()) >= prio(ch[i]))
{
computing(aba.top());
aba.pop();
if (aba.empty())break;
}
}
aba.push(ch[i]);
}
i++;
}
if (flag)fpx.push(x);
while( !aba.empty())
{
computing(aba.top());
aba.pop();
}
cout << fpx.top() << endl;
fpx.pop();
}
return 0;
}