如何用C#实现支持01读写的二进制串逐位取反图灵机
问题排查及修正方案
现有代码存在的核心问题
- 缺失核心取反逻辑:没有实现题目要求的读0写1、读1写0的写入操作,仅做了索引移动和状态切换,完全没有修改输入的字符数组内容。
- 状态设计不符合需求:当前定义的
CARRY、OVERFLOW等状态是用于加法进位场景的,按位取反的图灵机不需要这些状态,状态设计完全偏离需求。 - 语法不完整:代码中的
switch块、while循环、Main方法、Program类都没有闭合的大括号,属于语法错误,无法正常编译运行。 - 状态跳转逻辑错误:当前的跳转逻辑没有遍历所有待处理的二进制字符,仅处理单个字符就会进入
RETURN状态,无法完成整串取反。
修正后的实现代码
class Program { enum States { START, PROCESS, HALT }; static void Main(string[] args) { States state = States.START; // 边界符*包裹待处理二进制串 char[] input = "*101*".ToCharArray(); int index = 0; while(state != States.HALT) { switch (state) { case States.START: // 找到第一个非边界符进入处理状态 if (input[index] == '*') { index++; state = States.PROCESS; } break; case States.PROCESS: // 遇到右边界直接停机 if (input[index] == '*') { state = States.HALT; } // 读0写1 else if (input[index] == '0') { input[index] = '1'; index++; } // 读1写0 else if (input[index] == '1') { input[index] = '0'; index++; } break; } } // 输出处理结果 Console.WriteLine("处理结果:" + new string(input)); } }
内容的提问来源于stack exchange,提问作者adam hockney
相关产品推荐
相关产品推荐

