C++ 齿轮问题解法:静态数组实现
以下是 C++ 代码实现:\n\ncpp\n#include <iostream>\n#include <string>\n\nusing namespace std;\n\nint main() {\n int n;\n cin >> n;\n string directions;\n cin >> directions;\n \n int count = 0;\n for (int i = 0; i < n; i++) {\n if (directions[i] == 'L' && directions[(i+1)%n] == 'R') {\n count++;\n } else if (directions[i] == 'R' && directions[(i+1)%n] == 'L') {\n count++;\n }\n }\n \n cout << count << endl;\n \n return 0;\n}\n\n\n首先,我们读取输入的齿轮数量 n 和每个齿轮的方向字符串 directions。\n\n然后,我们使用一个循环遍历每个齿轮。对于每个齿轮,我们检查它和下一个齿轮的方向是否要求反向转动(一个逆时针,一个顺时针)。如果是这种情况,我们将计数器 count 加 1。\n\n最后,输出计数器 count 的值。\n\n这个解决方案的时间复杂度为 O(n),其中 n 是齿轮数量。\n\n注意: 此代码仅使用静态数组,满足题目要求。\n
原文地址: https://www.cveoy.top/t/topic/qxdS 著作权归作者所有。请勿转载和采集!