201903-2 二十四点
理解:写一个简单的计算器程序,判断结果是否为24;
计算器程序原理:
1.中缀表达式 转为 后缀表达式
2.计算后缀表达式
3.涉及到 计算符号的 优先级
参考:
代码
//24点
#include<iostream>
#include<stack>
#include<string>
using namespace std;
int to_int(char c){
return c - '0';
}
int to_r(char c){
if (c == 'x' || c == '/')return 2;
else if(c=='+'||c=='-')return 1;
}
int op(int a, int b, char c){
if (c == 'x'){
return a*b;
}
else if (c == '+'){
return a + b;
}
else if (c == '-'){
return a - b;
}
else{
return a/b;
}
}
int main(){
int n; cin >> n;
stack<char> st1,st2;
stack<int> st3;
string str;
for (int i = 0; i < n; i++){
cin >> str;
for (int j = 0; j < 7; j++){
if (str[j] >= '0'&&str[j] <= '9'){
st1.push(str[j]);
}
else{
if (st2.empty()){
st2.push(str[j]);
}
else if (to_r(str[j]) > to_r(st2.top())){
st2.push(str[j]);
}
else if (to_r(str[j]) <= to_r(st2.top())){
char c;
while (!st2.empty()&&to_r(str[j]) <= to_r(st2.top())){
c = st2.top();
st2.pop();
st1.push(c);
}
st2.push(str[j]);
}
}
}
while (!st2.empty()){
char c1 = st2.top();
st2.pop();
st1.push(c1);
}
while (!st1.empty()){
st2.push(st1.top());
st1.pop();
}
while (!st2.empty()){
if (st2.top() >= '0'&&st2.top() <= '9'){
st3.push(to_int(st2.top()));
st2.pop();
}
else{
int aa = st3.top(); st3.pop();
int bb = st3.top(); st3.pop();
st3.push(op(bb, aa, st2.top()));
st2.pop();
}
}
//cout << st3.top() << endl;
if (st3.top() == 24){
cout << "Yes" << endl;
}
else{
cout << "No" << endl;
}
while (!st2.empty()){
st2.pop();
}
while (!st1.empty()){
st1.pop();
}
while (!st3.empty()){
st3.pop();
}
}
//system("pause");
return 0;
}