简体   繁体   English

Java递归和整数两位数

[英]Java recursion and integer double digit

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 . 例如, doubleDigit(3487)将返回33448877

I'm stuck because I can't figure out how I would read each number in the digit I guess. 我被困住了,因为我无法弄清楚我怎么猜数字中的每个数字。

I did the same question when doing Building Java Programs. 在构建Java程序时,我做了同样的问题。 Here is my solution which works for negative and positive numbers (and returns 0 for 0). 这是我的解决方案,适用于负数和正数(并为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;
}

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. 要使用递归来执行此操作,请使用模数运算符(%),每次除以10,并向后累加结果字符串,直到达到基本情况(0),该情况无余可除。 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();
      }
    }

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而不是String的解决方案,则可以在下面使用以下解决方案(与Chris'极为相似,以0为基本情况):

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. 该函数当然受Java中long最大大小限制。

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. 您可以获取给定整数的String.valueOf(doubleDigit)表示形式,然后使用Commons StringUtils(在我看来,这是最简单的)来操作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. 如果您需要在此时返回另一个数字值(与新创建/处理的字符串相对),则可以执行Integer.valueOf(yourString)或类似的操作。

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): 我不再是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
} 

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. 请注意,我切换到long所以它可以再使用几个数字。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM