文章
1
粉丝
0
获赞
0
访问
43
#include <bits/stdc++.h>
using namespace std;
struct op{
char ch;
int pri;
};
int ans[100];
int flag[100]{0};
int cnt=0;
void getOp(char ch){//将当前运算符放入ans
flag[cnt]=1;//运算符
if(ch=='+') ans[cnt]=1;
else if(ch=='-') ans[cnt]=2;
else if(ch=='*') ans[cnt]=3;
else if(ch=='/') ans[cnt]=4;
else ans[cnt]=5;
cnt++;
}
int main(){
string s;
stack<op> st;
cin>>s;
int l = s.size();
int k=0;//记录当前字符串中连续数字的位数
for(int i=0;i<l;i++){//将当前字符串遍历
if(s[i]>='0'&&s[i]<='9'){//数字
k++;
if(i==l-1||s[i+1]<'0'||s[i+1]>'9'){
string num=s.substr(i-k+1,k);
ans[cnt++]=stoi(num);
k=0;
}
}else{//运算符
struct op temp;
temp.ch=s[i];
//设定优先级
if(s[i]=='+'||s[i]=='-'){
temp.pri=1;
}else if(s[i]=='*'||s[i]=='/'){
temp.pri=2;
}else temp.pri=3;
//根据栈顶元素判断出入栈
if(st.empty()) st.push(temp);
else{
while(st.top().pri>=temp.pri){//高优先级出栈
getOp(st.top()...
登录后发布评论
暂无评论,来抢沙发