题目描述
对于一个不存在括号的表达式进行计算
输入
存在多种数据,每组数据一行,表达式不存在空格
输出
输出结果
样例输入
6/2+3+3*4 734/2-56*2-7*8
样例输出
18 199
#include<iostream>
#include<stack>
#include<cstring>
#include<string>
using namespace std;
string s;
stack<int> ns;
stack<int> os;
int idx;
//注意5x5的优先级矩阵,一共就9个1
//因为同级的运算符得按照从左到右的顺序运算!!
//所以矩阵前三行都一样
int map[5][5]={
1,0,0,0,0,
1,0,0,0,0,
1,0,0,0,0,
1,1,1,0,0,
1,1,1,0,0
};
//因为c++函数没法一次返回两个值,所以这里用引用传值的方法
//不错的想法
void getnext(int &flag,int &num,int &op)
{
flag=0;
num=0;
int temp=0;
int c=1;
if(idx==0)
{
os.push(0);
}
if('0'<=s[idx]&&s[idx]<='9')
{
flag=0;
int last=0;
for(int i=idx;i<s.length();i++)
{
if('0'<=s[i]&&s[i]<='9')
{
last++;
}else
{
break;
}
}
//这样读出来的数字是反的 734读成437
//这个问题已经解决了
/*
for
value+=a[i]
value*=10
*/
for(int i=idx+last-1;i>=idx;i--)
{
if('0'<=s[i]&&s[i]<='9')
{
//cout<<"s[i]:"<<s[i]<<endl;
num+=c*(s[i]-'0');
c*=10;
}else
{
break;
}
}
idx+=last;
}
else
{
if(s[idx]=='+')
{
flag=1;
num=0;
op=1;
}
if(s[idx]=='-')
{
flag=1;
num=-1;
op=2;
}
if(s[idx]=='*')
{
flag=1;
op=3;
}
if(s[idx]=='/')
{
flag=1;
op=4;
}
idx++;
}
if(idx-1==s.length())
{
flag=1;
op=0;
return;
}
}
int main()
{
while(cin>>s)
{
idx=0;
while(!ns.empty())
{
ns.pop();
}
while(!os.empty())
{
os.pop();
}
int f,n,o;
while(idx<=s.length())
{
getnext(f,n,o);
//printf("标志:%d 数值:%d 符号:%d\n",f,n,o);
if(f==0)
{
ns.push(n);
// printf("数值栈中压入数字 %d\n",n);
}
else
{
if(!os.empty())
{
// printf("符号栈非空 %d\n",o);
if(map[o][os.top()]==1)
{
// printf("符号栈中压入运算符 %d\n",o);
os.push(o);
}
else
{
// printf("当前运算符小于栈顶运算符 %d\n",o);
//一直弹到大于栈顶符号优先级
while(map[o][os.top()]==0)
{
int top=os.top();
os.pop();//这注意!
int n1=ns.top();
ns.pop();
int n2=ns.top();
ns.pop();
if(top==1)
{
// printf("取两个数字运算 %d %d\n",n1,n2);
ns.push(n1+n2);
}
if(top==2)
{
// printf("取两个数字运算 %d %d\n",n1,n2);
ns.push(n2-n1);
}
if(top==3)
{
// printf("取两个数字运算 %d %d\n",n1,n2);
ns.push(n1*n2);
}
if(top==4)
{
// printf("取两个数字运算 %d %d\n",n1,n2);
ns.push(n2/n1);
}
}
//才压入该运算符
os.push(o);
//当符号栈中只有两个O,数值栈中只有最后一个计算结果的时候,运算结束
if(os.top()==0&&os.size()==2&&ns.size()==1)
{//计算结束
break;
}
}
}
// else
// {
//
// }
}
}
// printf("运算结果 %d\n",ns.top());
printf("%d\n",ns.top());
}
}