ccf 201903-2 二十四点

 

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

int calculate(int num1, int num2, char op){
	switch(op){
		case '+':
			return num1+num2;
		case '-':
			return num1-num2;
		case 'x':
			return num1*num2;
		case '/':
			return num1/num2;
	}
}
int main(){
	int n;
	cin >> n;
	int i = 0, j = 0;
	stack<int> nums;
	stack<char> ops;
	string result[n];
	char ch;
	while(j < n){
		while(i++ < 7){
			cin >> ch;
			if(ch != '+' && ch != '-' && ch != 'x' && ch != '/'){
				nums.push((int)(ch - '0'));
			}else{
				if(ch != '+' && ch != '-'){
					// 数字栈中只有0个或1个数字,无法运算,等待下一次符号输入 
					if(nums.size() >= 2){
						char op = ops.top();
						// 如果此次运算符为 * 或者 /
						// 查看上次运算符,如果是 * 或 / , 上次运算
						// 并将运算结果压入数字栈中 
						// 如果是 + 或 -  ,不执行上次运算,等待下次运算符时判断					
						if(op == 'x' || op == '/'){						
							int num2 = nums.top();
							nums.pop();
							int num1 = nums.top();
							nums.pop();												
							nums.push(calculate(num1, num2, ops.top()));
							ops.pop();							
						}						
					}
					ops.push(ch);								
				}else{
					// 数字栈中只有0个或1个数字,无法运算,等待下一次符号输入
					if(nums.size() >= 2){
						// 如果此次运算符为 + 或者 -, 则执行上次运算, 并将运算结果压入数字栈中 
						int num2 = nums.top();
						nums.pop();
						int num1 = nums.top();
						nums.pop();												
						nums.push(calculate(num1, num2, ops.top()));
						ops.pop(); 						
					}
					ops.push(ch);					
				}
			}									
		}	
		
		// 如果运算符栈内还有值,继续运算 
		while(!ops.empty()){
			char op = ops.top();
			int num2 = nums.top();
			nums.pop();
			int num1 = nums.top();
			nums.pop();												
			nums.push(calculate(num1, num2, ops.top()));
			ops.pop(); 	
		}
		
		if(nums.top() == 24){
			result[j++] = "Yes";
		}else{
			result[j++] = "No";
		}
		nums.pop();
		i = 0;	
	} 
		
	j = 0;
	while(j < n){
		cout << result[j++] << endl;
	}	
	return 0;
} 

这道题有个坑,题目中描述乘号用字母 'x' 代替,刚开始没注意,直接用的字母 '*',总是不能满分,后来才发现,审题要仔细!

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值