CCF 201903-2 二十四点 C++ 注意

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
思路:先用getline()读取整个字符串。利用一个栈,对字符串中的运算数边运算边入栈:遇到乘除,取出栈顶元素和字符串中该乘除号的下一个字符(运算数)进行乘除运算,然后把结果压入栈中;如果遇到减号,则把下一个运算数取负号然后压入栈中。然后对栈中所有的运算数做加法,判断最后的结果是否为24即可。

#include <iostream>
#include <stack>
#include <string>
using namespace std;
int main()
{
	int n;
	string str;
	cin >> n;
	cin.get();	
	for(int i=0;i<n;i++)
	{
		int sum=0;
		stack<int> s;
		getline(cin,str);
		for(int j=0;j<str.length();j++)
		{
			if(str[j]>='0'&&str[j]<='9')
			{
				s.push(str[j]-'0');
			}
			else if(str[j]=='x')
			{
				int temp=s.top()*(str[j+1]-'0');
				s.pop();
				s.push(temp);
				j++;
			}
			else if(str[j]=='/')
			{
				int temp=s.top()/(str[j+1]-'0');
				s.pop();
				s.push(temp);
				j++;
			}
			else if(str[j]=='-')
			{
				s.push(-(str[j+1]-'0'));
				j++;
			}
		}
		while(!s.empty())
		{
			sum+=s.top();
			s.pop();
		}
		if(sum==24) cout << "Yes" << endl;
		else  cout << "No" << endl;
	}
	return 0;
}

注意:栈的用法;
减法处的处理思想;
cin >> n后要处理空行;
str[i]-'0’换算成整数形式
只有当遇到运算符的时候才j++,跳过一下,遇到数字时直接存入,不跳过;
测试数据:

10
9+3+4x3
5+4x5x5
7-9-9+8
5x6/5x4
3+5+7+9
1x1+9-9
1x9-5/9
8/5+6x9
6x7-3x6
6x4+4/5
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值