开发者

Which of recursion method is better and why for reverse digits of integer?

public static int recursiveReverse(int number, int reversenumber){

    if(number <= 0) {
        return reversenumber;
    }

    reversenumber = reversenumber * 10 + (number % 10);
    number = number/10;

    return recursiveReverse(number, reversenumber);
}

OR

private static int reversenumber = 0;

public static int recursiveReverse(int number){

    if(number <= 0) {
        return reversenumber;
    }

    rev开发者_如何学Goersenumber = reversenumber * 10 + (number % 10);
    number = number / 10;

    return recursiveReverse(number);  
}


Definitely not the last one. Putting a state-holding variable in a static field is just asking for trouble. Not that you're necessarily designing for concurrency, but if you had multiple threads running this code, for example, the shared reverseNumber field would totally wreck everything.

I don't see any difference between the first and second. (Literally, they appear identical to me.)

If your goal is to simplify the calling convention by having a default value for the second parameter (reverseNumber), then simply overload your method:

public static int recursiveReverse(int number) {
    return recursiveReverse(number, 0);
}

private static int recursiveReverse(int number, int reverseNumber) {
    // your code goes here
}


I don't see any difference between the first and second example

but using a static variable in the third example is dangerous (you need to reset it each time and it's not threadsafe)


I think condition (n <= 0) adds extra 0 in the end. Comparing with 10 (n <= 10) returns correctly reversed integer

public int rev(int n){
    if(n <= 10) {
        return n;
    }
    return Integer.parseInt("" + (n % 10) + rev(n / 10));
}


Have a go with the following:

public int rev(int n){
    if(n <= 0) {
        return n;
    }
    return Integer.parseInt("" + (n % 10) + rev(n / 10));
}

This way you don't need a temporary variable to hold state and it satisfies the return type. Hope this helps!! :)


This is very shortest/simplest way in two lines code:

public static int reverseNumber(int n) 
{
    System.out.println(n % 10);
    return (n/10 > 0) ? reverseNumber(n/10) : n;
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜