c - 计算语句的真值
问题描述
我一直在努力解决这个问题:
我必须编写一个计算语句真值的递归代码(我也可以在函数中使用循环);
- 连接符:“&”(和)和“|” (或者)
- 值:1 和 0
- 该函数必须返回“1”或“0”
例如 -
对于语句 1,函数必须返回 1
对于语句 0,函数必须返回 0
对于语句 (1&1),函数必须返回 1
对于语句 (0|1),函数必须返回 1
所以基本上 0 & 0\1 = 0 , 1 | 1\0 = 1
对于更复杂的语句
(1&(1|0)) ; (1|0) 是 1,所以 (1&1) 是 1
((1|0)&(0&1)) ; (1|0) = 1, (0&1) = 0 --> (1&0)=0
(语句定义为字符串)
int st_value (char statement[], int length, int i) /* this can be changed*/
{
if (length == 1)
return statement[0];
if (statement[i]=='(' && statement[length-1]==')')
return st_val(statement, length--, i++);
else if (statement[i]=='(')
return st_val(statement, length, i++);
if (statement[i]=='0' || statement[i]=='1')
{
if (a[i+1] == '|')
return st_val(statement, length, i+2);
.....
}
if (statement[i]=='&')
.....
}
如果我必须遵循这个,代码会太长并且会有很多漏洞,比如当代码的某些部分返回 0 时......
解决方案
问题是,在编写函数时不允许使用指针、结构和树。
考虑到您的上述限制。
下面的代码通过将每个(exp)
表达式视为单独的表达式并最终组合结果来解决表达式。
int parse(char str[])
{
int i = 0;
int value = 0;
for (i = 0; str[i]; i++)
{
if (str[i] == '&')
{
i++;
if (str[i] == '('){
value = value && parse(&str[i+1]);
int brackCount = 1;
while(brackCount)
{
if (str[i] == '(') brackCount++;
else if (str[i] == ')') brackCount--;
i++;
}
i--;
}
else {
value = value && (str[i]-'0');
}
}
else if (str[i] == '|')
{
i++;
if (str[i] == '('){
value = value || parse(&str[i+1]);
int brackCount = 1;
while(brackCount)
{
if (str[i] == '(') brackCount++;
else if (str[i] == ')') brackCount--;
i++;
}
i--;
}
else {
value = value || (str[i]-'0');
}
}
else if (str[i] == '(') {
i++;
value = parse(&str[i]);
int brackCount = 1;
while(brackCount)
{
if (str[i] == '(') brackCount++;
else if (str[i] == ')') brackCount--;
i++;
}
i--;
}
else if (str[i] == ')')
{
return value;
}
else value = str[i]-'0';
}
return value;
}
注意:我用过幼稚的方法尝试重构它。
推荐阅读
- ios - 如何修复不为 iOS 构建的 React Native App
- angular - Angular - 如何通过选择器将事件绑定到 HTML 元素?
- python - 在 Tkinter 中更新文本小部件中的值
- reporting-services - 用于从 oracle 数据库中过滤数据集时,多值参数不起作用
- python - 根据视图中的计算字段对 django ListView 进行排序
- android - 如何使用复选框删除recyclerview项目?
- javascript - 在 SQL 中根据销售百分比创建客户集群
- python - Kivy App:TypeError:object.__init__() 只接受一个参数(要初始化的实例)
- php - 无法更改 WordPress 预览帖子链接(带有 preview_post_link)
- python - 从一列和一行创建矩阵