Java递归和整数双位数

发布于 2024-10-20 18:44:58 字数 144 浏览 2 评论 0原文

我试图将一个整数作为参数,然后使用递归将整数中的每个数字加倍。

例如,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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

—━☆沉默づ 2024-10-27 18:44:58

要使用递归执行此操作,请使用模运算符 (%),每次除以 10 并向后累加生成的字符串,直到到达基本情况 (0),此时没有任何内容可除。在基本情况下,您只需返回一个空字符串。

String doubleDigit(Integer digit) {

      if (digit == 0) {
        return "";
      } else {
        Integer thisDigit = digit % 10;
        Integer remainingDigits = (digit - thisDigit) / 10;
        return doubleDigit(remainingDigits) + thisDigit.toString() + thisDigit.toString();
      }
    }

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.

String doubleDigit(Integer digit) {

      if (digit == 0) {
        return "";
      } else {
        Integer thisDigit = digit % 10;
        Integer remainingDigits = (digit - thisDigit) / 10;
        return doubleDigit(remainingDigits) + thisDigit.toString() + thisDigit.toString();
      }
    }
画尸师 2024-10-27 18:44:58

如果您正在寻找返回 long 而不是 String 的解决方案,您可以使用下面的解决方案(与 Chris 非常相似,假设 0 作为基本情况):

long doubleDigit(long amt) {
    if (amt == 0) return 0;     
    return doubleDigit(amt / 10) * 100 + (amt % 10) * 10 + amt % 10;        
}

该函数当然受到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):

long doubleDigit(long amt) {
    if (amt == 0) return 0;     
    return doubleDigit(amt / 10) * 100 + (amt % 10) * 10 + amt % 10;        
}

The function is of course limited by the maximum size of a long in Java.

街角卖回忆 2024-10-27 18:44:58

我在做Building Java Programs 的时候也问过同样的问题。这是我的解决方案,适用于负数和正数(对于 0 返回 0)。

public static int doubleDigits(int n) {
    if (n == 0) {
        return 0;
    } else {
        int lastDigit = n % 10;
        return 100 * doubleDigits(n / 10) + 10 * lastDigit + lastDigit;
}

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).

public static int doubleDigits(int n) {
    if (n == 0) {
        return 0;
    } else {
        int lastDigit = n % 10;
        return 100 * doubleDigits(n / 10) + 10 * lastDigit + lastDigit;
}
勿挽旧人 2024-10-27 18:44:58

这里不需要使用递归。

我不再是java人,但我可能使用的算法的近似值是这样的(在C#中工作,应该直接翻译为java):

int number = 3487;
int output = 0;
int shift = 1;
while (number > 0) {
   int digit = number % 10;                 // get the least-significant digit       
   output += ((digit*10) + digit) * shift;  // double it, shift it, add it to output
   number /= 10;                            // move to the next digit
   shift *= 100;                            // increase the amount we shift by two digits
} 

这个解决方案应该可以工作,但现在我已经不厌其烦地编写它了,我意识到将数字转换为字符串并对其进行操作可能更清楚。当然,这会慢一些,但你几乎肯定不会关心这么小的速度差异:)

编辑:
好吧,所以你必须使用递归。您已经接受了一个完美的答案,但这是我的:)

private static long DoubleDigit(long input) {       
    if (input == 0) return 0;                      // don't recurse forever!
    long digit = input % 10;                       // extract right-most digit
    long doubled = (digit * 10) + digit;           // "double" it
    long remaining = input / 10;                   // extract the other digits
    return doubled + 100*DoubleDigit(remaining);   // recurse to get the result
}

注意我切换到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):

int number = 3487;
int output = 0;
int shift = 1;
while (number > 0) {
   int digit = number % 10;                 // get the least-significant digit       
   output += ((digit*10) + digit) * shift;  // double it, shift it, add it to output
   number /= 10;                            // move to the next digit
   shift *= 100;                            // increase the amount we shift by two digits
} 

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 :)

private static long DoubleDigit(long input) {       
    if (input == 0) return 0;                      // don't recurse forever!
    long digit = input % 10;                       // extract right-most digit
    long doubled = (digit * 10) + digit;           // "double" it
    long remaining = input / 10;                   // extract the other digits
    return doubled + 100*DoubleDigit(remaining);   // recurse to get the result
}

Note I switched to long so it works with a few more digits.

深府石板幽径 2024-10-27 18:44:58

您可以获取给定整数的 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文