2019-03-02 二十四点【stack】

 

我刚开始寻思着,测试样例里边这么多例子,测试样例过了应该就没问题了吧,然后提交才得了30分。。。

原来是7-9-9+8 我刚开始错误的运算顺序是先算9+8,结果15入栈,再算9-15,结果-8入栈,再算7--8,结果为15,虽然不等于24,但是很明显这样做是错的呀,竟然犯了这种小学减法加括号的错误,还好找出来了

注意这个式子 :-first+second=-(first-second)  -first-second=-(first+second)

下边是一个丑丑的流程图(我也不知道为什么这么丑,但是思路应该是对的)

#include<iostream>
#include<stack>
using namespace std;

int main(){
	int n;
	char s[9];
	stack<int> number;
	stack<char> op;
	scanf("%d",&n);
	while(n--){
		scanf("%s",&s);
		while(!number.empty()){
			number.pop();
		}
		for(int i=0;i<7;i++){
			if(isdigit(s[i])){
				s[i]=s[i]-'0';
				if(op.empty()){
					number.push(s[i]);
				}
				else if(op.top()=='x'){   //如果是乘号 
					int last=number.top();
					number.pop();
					int res=last*s[i];
					number.push(res);
					op.pop();
				}
				else if(op.top()=='/'){   //如果是除号 
					int last=number.top();
					number.pop();
					int res=last/s[i];
					number.push(res);
					op.pop();
				}
				else{   //如果是加号或减号 
//					printf("else\n");
					number.push(s[i]);	
				}
			}
			else{
				op.push(s[i]);
			}

		}
		//cout<<number.top()<<endl;
		while(!op.empty()){
			char nowop=op.top();
			op.pop();
			int second=number.top();
			number.pop();
			int first=number.top();
			number.pop();
			int res=0;
			char lastop;
			if(!op.empty()){
				lastop=op.top();
				if(lastop=='-'){    //这个式子相当于 -first+second=-(first-second)  -first-second=-(first+second) 
					if(nowop=='+'){
						nowop='-';
					}
					else if(nowop=='-'){
						nowop='+';
					}
				}
			}
			
//			cout<<nowop<<endl; 
			if(nowop=='+'){
				res=first+second;
//				printf("first:%d second:%d res:%d\n",first,second,res);
				number.push(res);
			}
			else if(nowop=='-'){
				res=first-second;
//				printf("first:%d second:%d res:%d\n",first,second,res);
				number.push(res);
			}
		}
		if(number.top()==24){
			printf("Yes\n");
		} 
		else{
			printf("No\n");
		}
//		printf("%d\n",number.top());
		number.pop();
	}
	return 0;
}

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值