3302.表达式求值(AcWing)

在这里插入图片描述

思路

一个map确定符号的优先级 两个栈分别存储数字和符号
首先检查是不是数字, 是,然后避免多位数字比如101*100 将101压入栈中还要检查 ‘1’后面是不是还有数字,不检查就会直接压入1而不是101
其次确定是符号,
如果是左括号 直接压入
如果是有括号 进行计算 直到找到左括号 然后弹出
如果都不是 则判断压入符号和栈顶符号的优先级,栈顶符号优先级高,则直接进行计算 调用计算函数, 然后压入该压入的计算符号 如果压入符号优先级高 则直接压入
最后 判断符号栈是否空 不空,则进行计算 知道空为止

AC代码
#include<iostream>
#include<algorithm>
#include<stack>
#include<string>
#include<map>
using namespace std;

stack<int>ans;
stack<char>op;
map<char,int>opp={{'+',1},{'-',1},{'*',2},{'/',2},{'(',0},{'(',0}};

void cal()
{
	int a=ans.top();
	ans.pop();
	int b=ans.top();
	ans.pop();
	char o=op.top();
	op.pop();
	int c;
	if(o=='+')c=a+b;
	if(o=='-')c=b-a;
	if(o=='*')c=a*b;
	if(o=='/')c=b/a;
	
	ans.push(c);
}
int main()
{
	string s;
	
	cin>>s;
	
	for(int i=0;i<s.length();i++)
	{
		
		if(isdigit(s[i]))
		{
			int an=0;
			while(isdigit(s[i]))
			{
				an=an*10+s[i]-'0';
				i++;
			}
			ans.push(an);
			i--;
		}
		 
		else
		{
			
			 if(s[i]=='(')
			op.push(s[i]);
			else if(s[i]==')')
			{
				while(op.top()!='(')
				cal();
				op.pop();
			}
			else 
			{
				while(op.size()&&opp[op.top()]>=opp[s[i]])
				cal();
				op.push(s[i]);
			}
			
		}
	}
	while(op.size())
	{
		cal();
	}
	cout<<ans.top()<<endl;
	return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值