利用STL 中的Stack 求逻辑表达式的值
2018-03-18 22:14
357 查看
利用STL 中的Stack 求逻辑表达式的值
今天上午做网易游戏的笔试题目,其中有一道是求合法表达式的逻辑值,在做的过程中,一直以为是要用到后缀表达式来进行求解,并且对逻辑符号和数字没有进行很好的处理,晚上的时候仔细想了一下,发现并不是很难,通过一个字符栈和一个数字栈,利用表达式中的每一个逻辑符号都带有一个括号的特点,首先利用循环不断弹出字符栈中的元素,直到找到第一个不是括号的操作符。然后根据这个操作符选择弹出数字栈中的元素个数,并把逻辑值重新压入数字栈中。
今天上午做网易游戏的笔试题目,其中有一道是求合法表达式的逻辑值,在做的过程中,一直以为是要用到后缀表达式来进行求解,并且对逻辑符号和数字没有进行很好的处理,晚上的时候仔细想了一下,发现并不是很难,通过一个字符栈和一个数字栈,利用表达式中的每一个逻辑符号都带有一个括号的特点,首先利用循环不断弹出字符栈中的元素,直到找到第一个不是括号的操作符。然后根据这个操作符选择弹出数字栈中的元素个数,并把逻辑值重新压入数字栈中。
#include<iostream> #include<vector> #include<algorithm> #include<stack> using namespace std; int main() { int N; cin >> N; //这个字符串数组就是用来测试用的,在笔试的时候通过循环读入合法表达式 string s[4] = {"(!0)","(0|(1&0))","(0|(1&(!0)))","(0|(1&(!(0|(1&(0|(1&(0|(1&(0|(1&(0|(1&0)))))))))))))"}; for (int i = 0; i < N; ++i) { stack<char> c_temp; stack<int> n_temp; char c; int c_1, c_2; int ij; for (int k = 0; k < s[i].size(); ++k) { if (s[i][k] == '0' || s[i][k] == '1') n_temp.push(s[i][k]-'0'); //将字符转换为数字 else c_temp.push(s[i][k]); } while (1) { while (!c_temp.empty()) //在字符栈中找到第一个逻辑操作符 { if (c_temp.top() == ')' || c_temp.top() == '(') { c_temp.pop(); } else { break; } } if (c_temp.top() != '!') //根据逻辑操作符的种类进行不同的操作 { if (n_temp.size() > 1) { c_1 = n_temp.top(); n_temp.pop(); c_2 = n_temp.top(); n_temp.pop(); if (c_temp.top() == '&') //进行逻辑与操作 { ij = c_1 & c_2; n_temp.push(ij); } else //进行逻辑或操作 { ij = c_1 | c_2; n_temp.push(ij); } c_temp.pop(); //弹出操作符 } } else //进行逻辑非操作 { ij = !(n_temp.top()); n_temp.pop(); n_temp.push(ij); c_temp.pop(); //弹出操作符 } if (c_temp.empty()==0 && n_temp.size() == 1) { cout << n_temp.top() << endl; //输出最终的逻辑表达式的值 break; } } } system("pause"); return 0; }
相关文章推荐
- 利用stack计算后缀表达式
- 利用STL计算后缀表达式
- 利用栈求逻辑运算表达式的真值
- C++利用STL的stack将十进制转化为八进制
- C++用后缀表达式(逆波兰)求四则表达式值,采用STL中的stack
- 利用VC设计简易逻辑表达式词法分析器
- 利用STL容器stack实现一个简单的计算器
- 利用正则表达式作为string.split seprator
- stl之heap、stack的用法
- 转载:linux shell 逻辑运算符、逻辑表达式详解
- C++11标准 STL正则表达式 验证电子邮件地址
- 利用正则表达式计算含有中文的字符串长度
- 利用正则表达式, 验证控制文本框的输入字符类型
- 从零开始学C++之STL(十一):容器适配器(stack、 queue 、priority_queue)源码浅析与使用示例
- 利用STL中的map来写一个自己的命令行界面
- 利用正则表达式, 验证控制文本框的输入字符类型
- C++11标准 STL正则表达式 验证电子邮件地址
- 移动端利用OpenGL展示3D模型文件STL
- shell 比较逻辑表达式
- 利用正则表达式限制网页表单里的文本框输入内容