CCF认证 2019-03 02二十四点

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

#include<cstdio>
#include<cstring>
#include<stack>
using namespace std;

int n;
char str[10];

stack<int> num;
stack<char> sign; 

int main(){
	scanf("%d",&n);
	getchar(); 
	for(int i=0;i<n;i++){
		gets(str);
	
		while(!num.empty()) num.pop();	
		while(!sign.empty()) sign.pop();
		
		int j=0;
		while(j<strlen(str)){
			if(str[j]>'0' && str[j]<='9'){
				num.push(str[j]-'0');
			} 
			else{
				if(str[j]=='+'){
					sign.push('+');
				}
				else if(str[j]=='-'){ 
					num.push((str[j+1]-'0')*(-1));
					sign.push('+');
					j++;
				}
				else if(str[j]=='x'){ 
					int lhs=num.top();
					num.pop();
					num.push(lhs*(str[j+1]-'0'));
					j++;
				}
				else if(str[j]=='/'){
					int lhs=num.top();
					num.pop();
					num.push(lhs/(str[j+1]-'0'));
					j++;
				}
			}
			j++;
		}
		
		while(!sign.empty()){ 
			int rhs=num.top();
			num.pop();
			int lhs=num.top();
			num.pop();
			sign.pop();
			num.push(lhs+rhs);
		}
		
		int ans=num.top();
		if(ans==24) printf("Yes\n");
		else printf("No\n");
		
	}
	
	return 0;
}

解释:
该题用栈的相关知识进行解决,如果只有四个数字,并且乘除优先于加减,遇到乘除就直接出栈进行运算,而把加减进行存储,当乘除完成后,把剩余的加减运算进行从左往右的顺序加减它们。

发布了167 篇原创文章 · 获赞 15 · 访问量 6152

猜你喜欢

转载自blog.csdn.net/Re_view/article/details/100805590