2021-10-15每日刷题打卡
作者:互联网
一、信息学oj-1358:中缀表达式值(expr)
1.1 问题描述
1.2 问题解决
#include <cstdio>
#include <iostream>
#include <string>
#include <stack>
#include <cmath>
using namespace std;
stack<int> nums;
stack<char> operators;
int priority(char ch)
{
if(ch == '+' || ch == '-') return 1;
if(ch == '/' || ch == '*') return 2;
if(ch == '^') return 3;
return 0;
}
void calc()
{
int a = nums.top();
nums.pop();
int b = nums.top();
nums.pop();
char ch = operators.top();
operators.pop();
if(ch == '+') nums.push(a+b);
else if(ch == '-') nums.push(b-a);
else if(ch == '*') nums.push(a*b);
else if(ch == '/') nums.push(b/a);
else if(ch == '^') nums.push(pow(b,a));
}
bool check(string str)
{
stack<char> s;
for(int i = 0; str[i] != '@'; i++)
{
if(str[i] == '(')
s.push(str[i]);
if(str[i] == ')')
if(!s.empty())
s.pop();
else
return false;
if(str[i] == '/' && str[i+1] == '0')
return false;
}
return true;
}
int main()
{
string str;
cin >> str;
if(!check(str)) { cout << "NO" << endl; return 0; }
int num = 0;
bool flag = false;
for(int i = 0; str[i] != '@'; i++)
{
if(str[i] >= '0' && str[i] <= '9')
{
num = num*10 + str[i] - '0';
flag = true;
}
else
{
if(flag)
{
nums.push(num);
flag = false;
num = 0;
}
if(str[i] == '(')
{
operators.push(str[i]);
continue;
}
if(str[i] == ')')
{
while(operators.top() != '(') calc();
operators.pop();
continue;
}
while(!operators.empty() && priority(operators.top()) >= priority(str[i])) calc();
operators.push(str[i]);
}
}
if(flag) nums.push(num);
while(!operators.empty()) calc();
cout << nums.top() << endl;
return 0;
}
标签:10,ch,15,nums,operators,str,push,return,打卡 来源: https://blog.csdn.net/soulandlove/article/details/120790702