Description
输入中缀算术表达式S,S中的操作数为非负整数,只含+,-和*,/运算,也可能含有括号(),运算符的计算顺序和实际四则运算的计算顺序相同. 输出表达式S的值. 注意除法运算只取整数部分,例如1/2=0.
Input
输入有多组数据.
每组数据是一个算术表达式S,S的长度不超过100. 输入的S保证合法,而且不包含多余的空格或制表符. S的操作数、中间结果和最终结果都不会超过int类型的范围,也不会出现除数为0的情况.
输入以#号结束.
Output
对于每个算术表达式S,输出S的值,每个输出占一行.
Sample Input
1 478+522 (478+522)*10 1/2-1 #
Sample Output
1 1000 10000 -1
Problem Source: 林瀚
#include<iostream>
#include<stack>
#include<string>
#include<sstream>
using namespace std;
//获取优先级
int getPriority(char a)
{
if(a=='+'||a=='-')
{
return 1;
}
if(a=='*'||a=='/'){
return 2;
}
//左括号
return 0;
}
//字符串转整数
int str2num(string s)
{
int number;
stringstream ss(s);
ss>>number;
return number;
}
//操作结果
void operation(stack<int> &result,char c)
{
if(c == '+'){
int tmp;
int a = result.top();
result.pop();
int b = result.top();
tmp = b + a;
result.pop();
result.push(tmp);
}
if(c == '-'){
int tmp;
int a = result.top();
result.pop();
int b = result.top();
tmp = b - a;
result.pop();
result.push(tmp);
}
if(c == '*'){
int tmp;
int a = result.top();
result.pop();
int b = result.top();
result.pop();
tmp = b * a;
result.push(tmp);
}
if(c == '/'){
int tmp;
int a = result.top();
result.pop();
int b = result.top();
result.pop();
tmp = b / a;
result.push(tmp);
}
}
int main()
{
string input;
cin>>input;
while(input != "#")
{
stack<int> result;
stack<char> s;
int number[50];
char operate[50];
string tmp_num;
int size = 0;
//顺序扫描中缀表达式,把连续的数字整体截出来
for(int i = 0;i < input.size();++i)
{
//如果是数字
if(input.at(i) <= '9' && input.at(i) >= '0')
{
tmp_num.push_back(input.at(i));
if(i==input.size()-1){
number[size] = str2num(tmp_num);
tmp_num.clear();
++size;
}
}
else{
if(!tmp_num.empty()){
number[size] = str2num(tmp_num);
tmp_num.clear();
++size;
}
operate[size] = input.at(i);
number[size] = -1;
++size;
}
}
//后缀转前缀
for(int j=0;j<size;++j)
{
//如果是数字
if(number[j] != -1)
{
result.push(number[j]);
}
//如果是符号
else
{
//如果是左括号
if(operate[j] == '(')
{
s.push('(');
}
//如果是右括号
else if(operate[j] == ')')
{
while(s.top()!='('){
operation(result,s.top());
s.pop();
}
if(s.top() == '('){
s.pop();
}
}
//如果是算术运算符
else
{
if(s.empty()){
s.push(operate[j]);
}
else{
while(!s.empty()){
if(getPriority(operate[j]) > getPriority(s.top())){
s.push(operate[j]);
break;
}
else{
operation(result,s.top());
s.pop();
}
}
if(s.empty()){
s.push(operate[j]);
}
}
}
}
}
while(!s.empty()){
operation(result,s.top());
s.pop();
}
cout<<result.top()<<endl;
while(!result.empty())
{
result.pop();
}
cin>>input;
}
return 0;
}