CCF 二十四点

 

#include <iostream>
#include <algorithm>
#include <cmath>
#include <stack>
using namespace std;
int operate(int a,char theta,int b){//计算函数
	switch(theta){
		case '+':{
			return a+b;
		}
		case 'x':{
			return a*b;
		}
		case '/':{
			return a/b;
		}
	}
}

int main(){
	ios::sync_with_stdio(false);//使cin和scanf一样快
    int n;
    stack<int> pf;
    stack<char> pc;
    cin>>n;
    int j=n;
    while(j--){
    	char s[7];
    	int a,b;
    	cin>>s;
    	while(!pf.empty())//初始化清零
			pf.pop();
		while(!pc.empty())
			pc.pop();
    	for(int i=0;i<7;++i){
    		if(i%2!=0){//i是奇数 
    			pc.push(s[i]);
    			if(pc.top()=='x'||pc.top()=='/'){  //* /直接从左往右运算
		    		a=pf.top();pf.pop();
		    		b=s[++i]-'0';
		    		pf.push(operate(a,pc.top(),b));
		    		pc.pop();
				}
				else if(pc.top()=='-'){  //遇到减号看成负数整体,只做加法运算
//+ -也要从左往右运算,易错:容易使用结合律而忘记提负号要改变括号内的符号
					pf.push(-(s[++i]-'0'));
					pc.pop();
					pc.push('+');
				}	
			}
    		else
    			pf.push(s[i]-'0');
		}
		while(!pc.empty()){//进行+运算,直到运算符栈空
			b=pf.top();pf.pop();
			a=pf.top();pf.pop();
			pf.push(operate(a,pc.top(),b));
			pc.pop();
		}
		if(pf.top()==24)//判断结果
			cout<<"Yes"<<endl;
		else
			cout<<"No"<<endl;
		
	}
    return 0;
}

输入样例:

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

输出样例: 

Yes
No
No
Yes
Yes
No
No
No
Yes
Yes

样例解释 :

9+3+4 × 3 = 24
5+4 × 5 × 5 = 105
7 − 9 − 9+8= −3
5 × 6/5 × 4 = 24
3 + 5 + 7 + 9 = 24
1 × 1+9 − 9=1
1 × 9 − 5/9 = 9
8/5 + 6 × 9 = 55
6 × 7 − 3 × 6 = 24
6 × 4 + 4/5 = 24

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值