CSP 201903-2 二十四点 C++满分题解

本文介绍了如何用C++中的栈技术解析并计算带有运算符的算术表达式,遵循先乘除后加减的规则。

解题思路:

1.使用栈来分别存储数字和操作符

2.如果是数字,直接放入数字栈

3.如果是操作符:如果是乘法或者除法操作符,可以直接弹出数字栈的顶部两个数用来计算,计算                              结果放入数字栈

                            如果是加法,优先级低于乘除,不能直接计算,放入操作符栈

                            如果是减法,优先级低于乘除,不能直接计算,当成加法入栈,此外数字栈顶部                              数字要改变符号

4.第一轮遍历后计算完所有乘除,开始计算加法,每次从数字栈弹出两个数,操作符栈弹出一个操作符,数字相加后放入数字栈,直到操作符栈为空为止

#include<bits/stdc++.h>
using namespace std;

int main()
{
	int n;
	cin>>n; 
	
	while(n--)
	{
		string str;
		cin>>str;  //输入字符串
		stack<int> num;  //存储数的栈 
		stack<char> op;  //存储操作符的栈 
	    
		for(int i=0;i<str.length();i++)
		{
			if(i%2==0)  //这些位置是数字
			{
				int t=str[i]-'0';  //字符转数字
				num.push(t); 
			}

            //如果前一个字符是操作符
			if(i!=0&&str[i-1]=='x')  //乘除直接计算
			{
				int a=num.top();
				num.pop();
				int b=num.top();
				num.pop();
				int t=a*b;
				num.push(t);
			}
			else if(i!=0&&str[i-1]=='/')
			{
				int a=num.top();
				num.pop();
				int b=num.top();
				num.pop();
				int t=b/a;
				num.push(t);
			}
			else if(i!=0&&str[i-1]=='+')  //加法入栈
			{
				op.push(str[i-1]);
			}
			else if(i!=0&&str[i-1]=='-')  //减法改变符号后入栈
			{
				op.push('+');
				int t=num.top();
				num.pop();
				t=t*(-1);
				num.push(t);
			}
		}
		
		while(!op.empty())  //处理加法和剩余数字
		{
			char t=op.top();
			op.pop();
			int a=num.top();
			num.pop();
			int b=num.top();
			num.pop();
			int tt=a+b;
			num.push(tt);
		}
		int s=num.top();
		if(s==24)  cout<<"Yes"<<endl;
		else  cout<<"No"<<endl;
	}
	
	return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

小瑾比个耶

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值