Title Description
The main purpose of this question is the priority problem-solving ideas to solve the problem with a stack of four operations.
The key point of this problem is how to deal with priority issues operators correctly, you can use two stacks to solve this problem. A is the operand stack, the other operator stack.
When traversing the current arithmetic expression string will have five cases:
- The current character is a number.
If the current character is a number, then it can be directly converted into corresponding integers and pressed into the operand stack. - The current character is a plus
due to the addition of lower priority than multiplication and division, it is not directly adding to first add operator number into the stack. - Minus the current character is the
subtraction of the same priority as addition, operation can not be performed directly. For convenience herein, the subsequent operation, unified form to convert ab a + (- b) in the form of subtraction is calculated. Is about plus operator is pressed into the stack, the second operand negated after the press-fitting operand stack. - The current character is a multiplication sign
multiplication is the highest priority in this question, the operation can be performed directly. Back to the operand operand stack top element and multiplication multiply the result pushed again operand stack. - Current character is the division sign
division of the same priority as the multiplication operation above.
When been traversed arithmetic expressions, multiplication and division instructions formulas have been completed, only the following addition (subtraction have been converted into an adder), the operator until the stack is empty, the top element the final result is operand. Finally, take this number and 24 for comparison can be.
#include <iostream>
#include <string>
#include <string.h>
#include <stack>
using namespace std;
//二十四点游戏 ,特别注意运算符的优先级问题!!!用堆栈来解决
int main() {
int n; //表达式的个数
string str; //暂存当前表达式
int i, j;
int result[100] = {0}; //1代表计算结果是24, 0代表不是
stack<int> num; //运算数栈
stack<char> op; //运算符栈
cin >> n;
for (i = 0; i < n; i++) {
cin >> str;
for (j = 0; j < str.length(); j++) {
if (isdigit(str[j])) { //是数字
num.push(str[j] - '0');
} else if (str[j] == '+') {
op.push('+');
} else if (str[j] == '-') { //将减法转换成加法
op.push('+');
num.push(-(str[j + 1] - '0'));
j++;
} else if (str[j] == 'x') { //直接计算乘法
int num1 = num.top();
num.pop();
num.push(num1 * (str[j + 1] - '0'));
j++;
} else if (str[j] == '/') { //直接计算除法
int num1 = num.top();
num.pop();
num.push(num1 / (str[j + 1] - '0'));
j++;
}
}
while (!op.empty()) {
int num1 = num.top();
num.pop();
int num2 = num.top();
num.pop();
num.push(num1 + num2);
op.pop();
}
if (num.top() == 24) {
result[i] = 1;
}
num.pop(); //清空操作数栈
}
for (i = 0; i < n; i++) {
if (result[i] == 0) {
cout << "No" << endl;
} else {
cout << "Yes" << endl;
}
}
return 0;
}