2021-10-15每日刷题打卡

2021-10-15每日刷题打卡,第1张

2021-10-15每日刷题打卡 一、信息学oj-1358:中缀表达式值(expr) 1.1 问题描述

1.2 问题解决
#include 
#include 
#include 
#include 
#include 
using namespace std;

stack nums;
stack 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 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;
}

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/3971503.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-10-21
下一篇 2022-10-21

发表评论

登录后才能评论

评论列表(0条)

保存