递归连接两个整数
我需要编写一个函数,它接收两个正整数并将它们连接起来返回。
示例: Cat(12,13) 返回 1213
我知道如何以迭代方式执行此操作,它会是这样的:
int Cat(int num1, int num2)
{
int temp = num2;
while (temp > 0)
{
num1 *= 10;
temp /= 10;
}
return num1 + num2;
}
但是当我使用递归时,我无法使用将用于计算数字的临时变量,并且如果使用该参数我将失去它的价值。
I need to write a function which receives two positive integers and returns them concatenated.
Example: Cat(12,13) returns 1213
I know how to do this the iterative way, it would be something like this:
int Cat(int num1, int num2)
{
int temp = num2;
while (temp > 0)
{
num1 *= 10;
temp /= 10;
}
return num1 + num2;
}
But when I use recursion I can't use the temporary variable which will be used to count the digits, and if use the parameter I will lose its value.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(9)
您可以添加第三个参数来充当某种计数器:
You could add a third parameter to act as a sort of counter:
这不是“现实生活”的任务,不是吗?无论如何,这是我的主张(递归且没有第三个参数)
This is not a "real life" task, is it? Anyway here's my proposition (recursive and without the third parameter)
您需要递归例程一次处理一位数字,因此调用链将如下所示:
因此您的函数将如下所示:
You need your recursive routine to process one digit at a time, so the call chain would look like this:
So your function will look something like this:
您使用什么语言?您可以简单地将它们转换为字符串并以这种方式连接它们。
What language are you using? you could simply cast them as strings and concatenate them that way.
我不确定你是否把这个练习作为家庭作业——在这种情况下,我要说的可能对你不起作用。
但是,假设您不会将作业问题重新发布到网络上并且您只需要完成此操作,您是否考虑过简单的操作:
在函数出口处将其 (Java伪代码)
I'm not sure if you're engaged in this excercise as homework - in which case what I'm about to say may not work for you.
But assuming you wouldn't re-post your homework question to the Web and You Just Need To Get This Done, have you considered simply:
for example (in Java pseudo code)
为了将 MrGlass 所说的话编入法典,为什么不使用以下代码:
?
To codify what MrGlass said, why not use this code:
?
为什么要用递归来做呢?
python 中的代码:
Why do it with recursion anyway?
Code in python:
这就是它在Scheme中的解决方式:
[它可能包含语法错误,我没有测试它。]
在具有嵌套函数的类C语言中:
在尾部调用优化之后,这会展开为以下内容:
This is how it would have been solved in Scheme:
[It might contain syntax errors, I didn't test it.]
In a C-like language with nested functions:
After tail-call optimization, this gets unrolled into the following: