首页 > 解决方案 > 计算语句的真值

问题描述

我一直在努力解决这个问题:

我必须编写一个计算语句真值的递归代码(我也可以在函数中使用循环);

例如 -

所以基本上 0 & 0\1 = 0 , 1 | 1\0 = 1

对于更复杂的语句

(语句定义为字符串)

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 时......

标签: crecursion

解决方案


问题是,在编写函数时不允许使用指针、结构和树。

考虑到您的上述限制。

下面的代码通过将每个(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;
}

注意:我用过幼稚的方法尝试重构它。


推荐阅读