将字符串(如 (0&(1|0)|1) 和 (0|1) 转换为其对应的真值
Transform a string such as (0&(1|0)|1) & (0|1) into it's corresponding truth value
我在一个采访论坛上发现了这个问题,觉得这是一个有趣的问题。用C++有什么简单的方法可以完成这项任务吗?例如,假设我们有函数声明:
bool _transform(string x);
/* x is a combination of (, ), 0, 1, &, and | such that all expressions
start with a open and ending brace, and the function evaluates the
strings actual truth value
*/
有什么有效且相对简单的方法可以做到这一点吗?我曾想过递归地用括号括起来,但这个问题似乎很难解决。
这只是表达式解析和求值的一个相当简单的练习,使用逻辑运算符而不是算术运算符。真的很琐碎。查找"递归下降表达式解析"或Dijkstra调车场算法。警告:有许多国产和其他类似的产品,其中大多数都有细微的缺陷或非线性性能。使用来源。
注意,标题中表达式的值为1.
这个问题的简单解决方案是基于堆栈的解析器。[递归下降是过分的。]
For each character in the string
If it's a value (0 1)
If top of stack is an operator
Pop operator and value, evaluate
Push value on the stack
If it's an operator (&|) push it on the stack
If it's a left parenthesis push it on the stack
If it's a right parenthesis pop the value and the LP, push the value
At end, pop the value off the stack.
需要更多的代码来优雅地处理错误,但你已经明白了。它也忽略了优先级。
这个概念很容易扩展到任何类型的算术表达式,但您需要处理优先级才能得到正确的答案。这有效地将表达式从中缀转换为后缀表示法,并动态求值。
相关文章:
- 如何将包含epoch时间的十六进制字符串转换为time_t
- 当字符串存储在变量中时,如何将字符串转换为wchar_t
- 如何将这个std::字符串转换为std::基本字符串
- 如何正确将字符串转换为标准::时间::system_clock::time_point?
- 如何在C++中将十六进制字符串转换为文本数据
- 需要帮助在 c++ 中将字符串转换为字符 ----错误 "const char *" 类型的值不能用于初始化 "char" 类型的实体
- 如何从字符串转换为双精度*
- C++:如何将 unix 时间的字符串转换为 *tm?(使用时间错误:"cannot convert 'String' to 'tm*' ")
- 如何在C++中将 Python 字符串转换为其转义版本?
- 如何在 C++11 中将标准::字符串转换为标准::u32字符串?
- 如何将整数字符串转换为整数的二维向量?
- 使用 "stringstream " 将字符串转换为整数
- 将字符串转换为浮点数或整数,而无需使用内置函数(如 atoi 或 atof)
- 将文件复制到自定义位置,存在字符串转换问题
- 将ANSI C字符串转换为UNICODE
- 如何将节点 V8 字符串转换为 C++ 字符串
- 在C++中将字符串转换为双精度,而无需科学记数法
- 使用从文件(stod、strtod、atof)中提取的数据C++从字符串转换为双精度.csv
- 如何在C++中将字符串转换为双精度?
- 将字符串转换为无符号字符数组/字节数组