问题描述
试题编号: | 201903-2 |
试题名称: | 二十四点 |
时间限制: | 1.0s |
内存限制: | 512.0MB |
问 题 描述: |
解题思路:其实这个题目是简化版的“表达式求值”,可以选择中缀表达式转后缀表达式再求值的方法;但是本题目无需使用那样复杂的过程(其实是我能力不行....想偷懒.....)。定义一个stack或者vector变量 num,存储计算过程中产生的数值,最后直接累加该数组/栈中的数值得到结果(首先num存储表达式的第一个数值,然后遍历剩余部分:当前符号为 'x' / '/'时,直接计算temp = a*b 还或者temp = a / b ,然后将temp的数值push进num中;若当前符号为‘-’,则将负数存入num;若是‘+’,continue;当初这里写为 i++ ,找了半天没有找到错误;若当前字符为数字,则直接存入num)。
实现代码如下:
#include<bits/stdc++.h>
using namespace std;
int main(){
int n;
scanf("%d",&n);
while(n--){
char str[10];
scanf("%s",&str);
stack<int> num;
num.push(str[0] - '0'); // 存入第一个数字
for(int i = 1; str[i] != '\0'; i++){
if(str[i] == 'x' ){
int pre = num.top();
num.pop();
int temp = pre*(str[++i] - '0');
num.push(temp);
}else if(str[i] == '/'){
int pre = num.top();
num.pop();
int temp = pre/(str[++i] - '0');
num.push(temp);
}else if(str[i] == '-'){
int temp = -1 * (str[++i] - '0');
num.push(temp);
}else if(str[i] == '+'){
continue;
}else if(str[i] >= '0' || str[i] <= '9'){
num.push(str[i] - '0');
}
}
int ans = 0;
while(!num.empty()){
int temp = num.top();
num.pop();
ans += temp;
}
if(ans == 24) printf("Yes\n");
else printf("No\n");
}
}
//测试样例
//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