Java递归和整数双位数
我试图将一个整数作为参数,然后使用递归将整数中的每个数字加倍。
例如,doubleDigit(3487)
将返回 33448877
。
我被困住了,因为我不知道如何读取我猜的数字中的每个数字。
I'm trying to take an integer as a parameter and then use recursion to double each digit in the integer.
For example doubleDigit(3487)
would return 33448877
.
I'm stuck because I can't figure out how I would read each number in the digit I guess.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
要使用递归执行此操作,请使用模运算符 (%),每次除以 10 并向后累加生成的字符串,直到到达基本情况 (0),此时没有任何内容可除。在基本情况下,您只需返回一个空字符串。
To do this using recursion, use the modulus operator (%), dividing by 10 each time and accumulating your resulting string backwards, until you reach the base case (0), where there's nothing left to divide by. In the base case, you just return an empty string.
如果您正在寻找返回 long 而不是 String 的解决方案,您可以使用下面的解决方案(与 Chris 非常相似,假设 0 作为基本情况):
该函数当然受到Java 中的 long 的最大大小。
If you're looking for a solution which returns an long instead of a String, you can use the following solution below (very similar to Chris', with the assumption of 0 as the base case):
The function is of course limited by the maximum size of a long in Java.
我在做Building Java Programs 的时候也问过同样的问题。这是我的解决方案,适用于负数和正数(对于 0 返回 0)。
I did the same question when doing Building Java Programs. Here is my solution which works for negative and positive numbers (and returns 0 for 0).
这里不需要使用递归。
我不再是java人,但我可能使用的算法的近似值是这样的(在C#中工作,应该直接翻译为java):
这个解决方案应该可以工作,但现在我已经不厌其烦地编写它了,我意识到将数字转换为字符串并对其进行操作可能更清楚。当然,这会慢一些,但你几乎肯定不会关心这么小的速度差异:)
编辑:
好吧,所以你必须使用递归。您已经接受了一个完美的答案,但这是我的:)
注意我切换到
long
,因此它可以使用更多的数字。There's no need to use recursion here.
I'm no longer a java guy, but an approximation of the algorithm I might use is this (works in C#, should translate directly to java):
This solution should work, but now that I've gone to the trouble of writing it, I realise that it is probably clearer to just convert the number to a string and manipulate that. Of course, that will be slower, but you almost certainly don't care about such a small speed difference :)
Edit:
Ok, so you have to use recursion. You already accepted a perfectly fine answer, but here's mine :)
Note I switched to
long
so it works with a few more digits.您可以获取给定整数的 String.valueOf(doubleDigit) 表示形式,然后使用 Commons StringUtils(我认为最简单)来操作字符串。
如果您需要在此时返回另一个数值(而不是新创建/操作的字符串),您可以执行
Integer.valueOf(yourString)
或类似的操作。You could get the
String.valueOf(doubleDigit)
representation of the given integer, then work with Commons StringUtils (easiest, in my opinion) to manipulate the String.If you need to return another numeric value at that point (as opposed to the newly created/manipulated string) you can just do
Integer.valueOf(yourString)
or something like that.