最近写模拟写的挺多的,甚至用模拟写了一个java计算器。。
这个题目意思很明确了:
直接模拟。把输入进来的中缀表达式转换为后缀表达式,然后根据求后缀表达式的方法求解即可。
#include <bits/stdc++.h>
using namespace std;
string str;
stack<string> st;
vector<string> v;
const int mode=10000;
bool isdigital(char s){
return (s>='0' && s<='9');
}
void init(string s,int len){//中缀表达式转后缀表达式
string temp = "";
for (int i=0;i<len;i++){
if(!isdigital(s[i])){
v.push_back(temp);
temp="";
string t = "a";
t[0]=s[i];
if(st.size() == 0){
st.push(t);
}
else{
if(s[i] == '*'){//当前是乘号,则只需要看栈中的首元素是否为乘号
while(!st.empty()){
string cur=st.top();
if(cur.compare("*") == 0){
v.push_back(cur);
st.pop();
}
else break;
}
st.push(t);
}
else{
while(!st.empty()){//当前是加号,无论栈中是什么元素都要压入vector(因为栈中的元素的优先级大于或等于加号)
string cur=st.top();
v.push_back(cur);
st.pop();
}
st.push(t);
}
}
}
else {
temp+=s[i];
}
}
v.push_back(temp);//加一次最后的数字
while(!st.empty()){//把储存运算符的栈中的所有元素按顺序压入vector
string cur=st.top();
v.push_back(cur);
st.pop();
}
}
int change(string s){//把字符串变成一个数字
int f=1;
int ans=0;
for (int i=s.length()-1;i>=0;i--){
ans+=f*(s[i]-'0');
f*=10;
}
return ans;
}
stack <int> ss;
void solve(){//后缀表达式求解
for (int i=0;i<v.size();i++){
string cur=v[i];
if(isdigit(cur[0])){
int t=change(cur) % mode;//取模
ss.push(t);
}
else{
int a=ss.top();
ss.pop();
int b=ss.top();
ss.pop();
int t;
if(cur[0]=='*') t= (b %mode)* (a%mode);//取模
else t=(b % mode + a % mode) % mode;
ss.push(t);
}
}
}
int main(){
cin>>str;
int len=str.length();
init(str,len);
solve();
printf("%d\n",ss.top());//输出栈顶元素即为答案
return 0;
}