Home Article Practice 算法

算法

2022-07-03 10:37  views:337  source:小键人2625807    

#include<iostream>
#include<string>
#include<stack>
#include<unordered_map>
using namespace std;
stack<int> number;
stack<char> op;
unordered_map<char,int> pp{{'+',1},{'-',1},{'*',2},{'/',2}};
void evalue()
{
int b=number.top();number.pop();
int a=number.top();number.pop();
int num=0;
if(op.top()=='+')num=a+b;
else if(op.top()=='-')num=a-b;
else if(op.top()=='*')num=a*b;
else num=a/b;
op.pop();
number.push(num);
}
int main()
{
string s;
cin>>s;//输入字符串
//遍历字符串
for(int i=0;i<s.size();i++)
{
if(isdigit(s[i]))//如果是数字字符就将其入number栈
{
int num=0,st=i;
while(st<s.size()&&isdigit(s[st]))
{
num=num*10+s[st++]-'0';
}
i=st-1;
number.push(num);
}
else if(s[i]=='(')
op.push(s[i]);
else if(s[i]==')')
{
while(op.size()&&op.top()!='(')
evalue();
op.pop();//取出左括号
}
else
{
//操作符
while(op.size()&&pp[s[i]]<=pp[op.top()])//这里注意要保证op的size不是空的 否则会越界
evalue();
op.push(s[i]);
}
}
while(op.size())
evalue();
cout<<number.top()<<endl;
return 0;
}



Disclaimer: The above articles are added by users themselves and are only for typing and communication purposes. They do not represent the views of this website, and this website does not assume any legal responsibility. This statement is hereby made! If there is any infringement of your rights, please contact us promptly to delete it.

字符:    改为:
去打字就可以设置个性皮肤啦!(O ^ ~ ^ O)