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

后端 未结 5 1918
予麋鹿
予麋鹿 2020-12-22 07:00
public static int recursiveReverse(int number, int reversenumber){

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

    reversenumber = reversenumber *         


        
相关标签:
5条回答
  • 2020-12-22 07:34

    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)

    0 讨论(0)
  • 2020-12-22 07:35

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

    0 讨论(0)
  • 2020-12-22 07:37

    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));
    }
    
    0 讨论(0)
  • 2020-12-22 07:41

    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 讨论(0)
  • 2020-12-22 07:47

    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
    }
    
    0 讨论(0)
提交回复
热议问题