1 Star 0 Fork 1

saigon/Algorithms

forked from charlieshu/Algorithms 
加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
T110281 中缀表达式求值简单版2.cpp 2.00 KB
一键复制 编辑 原始数据 按行查看 历史
charlie 提交于 2024-01-09 00:01 . move from github to gitee
#include <iostream>
#include <stack>
#include <string>
using namespace std;
struct num{
int n;
char c;
};
int main(){
string s;
stack<num> sta;
cin>>s;
num ans;
ans.n = s[0]-'0';
ans.c = '+';
for(int i=1;i<s.length();i++){
if(s[i+1] != '(' && s[i] != ')' && !((s[i] == '+' || s[i] == '-') && (s[i+2] == '*' || s[i+2] == '/'))){
if(s[i] == '+')
ans.n += s[i+1]-'0';
if(s[i] == '-')
ans.n -= s[i+1]-'0';
if(s[i] == '*')
ans.n *= s[i+1]-'0';
if(s[i] == '/')
ans.n /= s[i+1]-'0';
if((s[i] == '*' || s[i] == '/') && (s[i+2] == '+' || s[i+2] == '-')){
num a=sta.top();
sta.pop();
if(ans.c == '+'){
ans.n += a.n;
ans.c = a.c;
}
else{
ans.n = a.n-ans.n;
ans.c = a.c;
}
i++;
}
i++;
}
else{
if(s[i+1] == '('){
sta.push(ans);
ans.c = s[i];
ans.n = s[i+2]-'0';
i += 2;
}
else if(s[i] == ')'){
if(ans.c == '*' || ans.c == '/'){ //前有乘除
num a=sta.top();
sta.pop();
if(ans.c == '*')
ans.n *= a.n;
else
ans.n = a.n/ans.n;
ans.c = a.c;
}
else if(s[i+1] == '*' || s[i+1] == '/'){ //后有乘除
if(s[i+1] == '*')
ans.n *= s[i+2]-'0';
else
ans.n /= s[i+2]-'0';
i += 2;
}
else{ //无乘除
num a=sta.top();
sta.pop();
if(ans.c == '+'){
ans.n += a.n;
ans.c = a.c;
}
else{
ans.n = a.n-ans.n;
ans.c = a.c;
}
}
}
else{
sta.push(ans);
ans.c = s[i];
ans.n = s[i+1]-'0';
i++;
}
}
}
while(!sta.empty()){
if(ans.c == '+'){
ans.n += sta.top().n;
ans.c = sta.top().c;
}
else if(ans.c == '-'){
ans.n = sta.top().n-ans.n;
ans.c = sta.top().c;
}
else if(ans.c == '*'){
ans.n *= sta.top().n;
ans.c = sta.top().c;
}
else{
ans.n += sta.top().n/ans.n;
ans.c = sta.top().c;
}
sta.pop();
}
cout<<ans.n;
return 0;
}
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
C++
1
https://gitee.com/saigonshu/algorithm.git
git@gitee.com:saigonshu/algorithm.git
saigonshu
algorithm
Algorithms
master

搜索帮助

0d507c66 1850385 C8b1a773 1850385