思路
一个map确定符号的优先级 两个栈分别存储数字和符号
首先检查是不是数字, 是,然后避免多位数字比如101*100 将101压入栈中还要检查 ‘1’后面是不是还有数字,不检查就会直接压入1而不是101
其次确定是符号,
如果是左括号 直接压入
如果是有括号 进行计算 直到找到左括号 然后弹出
如果都不是 则判断压入符号和栈顶符号的优先级,栈顶符号优先级高,则直接进行计算 调用计算函数, 然后压入该压入的计算符号 如果压入符号优先级高 则直接压入
最后 判断符号栈是否空 不空,则进行计算 知道空为止
AC代码
#include<iostream>
#include<algorithm>
#include<stack>
#include<string>
#include<map>
using namespace std;
stack<int>ans;
stack<char>op;
map<char,int>opp={{'+',1},{'-',1},{'*',2},{'/',2},{'(',0},{'(',0}};
void cal()
{
int a=ans.top();
ans.pop();
int b=ans.top();
ans.pop();
char o=op.top();
op.pop();
int c;
if(o=='+')c=a+b;
if(o=='-')c=b-a;
if(o=='*')c=a*b;
if(o=='/')c=b/a;
ans.push(c);
}
int main()
{
string s;
cin>>s;
for(int i=0;i<s.length();i++)
{
if(isdigit(s[i]))
{
int an=0;
while(isdigit(s[i]))
{
an=an*10+s[i]-'0';
i++;
}
ans.push(an);
i--;
}
else
{
if(s[i]=='(')
op.push(s[i]);
else if(s[i]==')')
{
while(op.top()!='(')
cal();
op.pop();
}
else
{
while(op.size()&&opp[op.top()]>=opp[s[i]])
cal();
op.push(s[i]);
}
}
}
while(op.size())
{
cal();
}
cout<<ans.top()<<endl;
return 0;
}