题目链接:点击打开链接
sample input:
1 (-2)+3 (1-(2+3)) (1-2+3) (1-(+(2-3)))sample output:
1 1 -4 2 2题意是给出只有'+'、'-'、‘(’、')'和数字(0-9)的表达式,求结果。
对于如(-2)、(+2(2-3))的特殊情况应注意在‘(’后应补0。可用STL栈解决。
// source code of submission 840377, Zhongshan University Online Judge System
#include <iostream>
#include <stack>
#include <string>
using namespace std;
int main()
{
string s;
while(cin >> s)
{
stack<int> op1;
stack<char> op2;
int i;
char ch;
char tem;
int a, b;
for(i = 0; i < s.size(); ++i)
{
if(s[i] == '(')
op2.push(s[i]);
else if(s[i] == '+' || s[i] == '-')
{
if(i > 0 && s[i-1] == '(')
{
op1.push(0);
op2.push(s[i]);
continue;
}
if(op2.empty())
{
op2.push(s[i]);
continue;
}
if(op2.top() == '+' || op2.top() == '-')
{
b = op1.top();
op1.pop();
a = op1.top();
op1.pop();
ch = op2.top();
if(ch == '+')
op1.push(a+b);
else
op1.push(a-b);
op2.pop();
}
op2.push(s[i]);
}
else if(s[i] == ')')
{
ch = op2.top();
if(ch == '(')
op2.pop();
else
{
b = op1.top();
op1.pop();
a = op1.top();
op1.pop();
if(ch == '+')
op1.push(a+b);
else
op1.push(a-b);
i--;
op2.pop();
}
}
else
op1.push(s[i]-'0');
}
if(op1.size() == 1)
cout << op1.top() << endl;
else
{
b = op1.top();
op1.pop();
a = op1.top();
op1.pop();
if(op2.top() == '+')
cout << a + b << endl;
else
cout << a -b << endl;
}
}
return 0;
}