题解 | 计算表达式
计算表达式
https://www.nowcoder.com/practice/7b18aa6b7cc14f8eaae6b8acdebf890b
#include <stdio.h>
#include <string>
#include <stack>
#include <map>
using namespace std;
int main(){
char str[1024];
scanf("%s",str);
map<char,int> opPriority = {
{'\0',0},
{'+',1},{'-',1},
{'*',2},{'/',2},
};
stack<char> opStack;
stack<float> numStack;
string st_num;
for(int i=0;;i++){ //拼凑整数
if(str[i]>='0'&&str[i]<='9'){
st_num.push_back(str[i]);
}else{ //操作符或结束符 ,也标志上一个数字拼凑完成
float num = stof(st_num);
numStack.push(num);
st_num = "";
while(!opStack.empty()&&opPriority[str[i]]<=opPriority[opStack.top()]){ //如果当前字符优先级小于等于栈顶 ,循环进行操作
float r = numStack.top(); numStack.pop();
float l = numStack.top(); numStack.pop();
char op = opStack.top(); opStack.pop();
if(op=='+'){
numStack.push(l+r);
}else if(op=='-'){
numStack.push(l-r);
}else if(op=='*'){
numStack.push(l*r);
}else if(op=='/'){
numStack.push(l/r);
}
}
if(str[i]=='\0'){
printf("%d",(int)numStack.top());
break;
} else{
opStack.push(str[i]);
}
}
}
return 0;
}
