如何替换c++中字符串的字符用递归函数?
您好,我是 cpp 编程的初学者。我正在阅读 cpp 程序的一些示例,我看到了这个问题,但我无法解决它: 下面有一个从 0 开始的算法,前进的每一步都应该用 01 替换所有 0,将 1 替换为 10。输入是阶段数,输出是生成用递归函数解决此问题的数字。
这是例子:
1)0
2)01
3)0110
...
Input:3
Output:0110
我尝试过这个:
string generate(string &algorithm, int n) {
if (n <= 0)
return algorithm;
//confused?
}
int main() {
string algorithm = "0";
string new_algorithm;
long long int n, k;
cin >> n >> k;
new_algorithm = generate(algorithm, n);
return 0;
}
它应该是递归形式,但我也不能直接这样做! 任何帮助将不胜感激!
Hello I'm a beginner in cpp programming. I was reading some examples of cpp programs and i see this question but i couldn't solve it :
There's an algorithm below starting from 0 as each step that goes forward you should replace all 0's with 01 and 1's 10. The input is the number of stage and the output is the number that generates solve this with recursive function.
Here is the example:
1)0
2)01
3)0110
...
Input:3
Output:0110
I tried this:
string generate(string &algorithm, int n) {
if (n <= 0)
return algorithm;
//confused?
}
int main() {
string algorithm = "0";
string new_algorithm;
long long int n, k;
cin >> n >> k;
new_algorithm = generate(algorithm, n);
return 0;
}
It should be in recursive form but I can't do it straight too!
Any help would be appreciated!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
给出了递归次数,因此函数看起来像这样:
它有一个停止条件,它执行一个步骤(通过调用
replace
)并且它有递归调用。您需要添加的只是从
in
到next
。为此,最简单的方法是使用基于范围的循环并通过附加来构造新字符串。我试图不放弃整个解决方案:The number of recusions is given so the function will look something like this:
It has a stop condition, it executes a single step (by calling
replace
) and it has the recursive call.All you need to add is going from
in
tonext
. For this it is easiest to use a range based loop and construct the new string by appending. I am trying to not give away the whole solution: