Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Recursion Reverse

Tags:

java

recursion

public static String backwards(Integer x){
    if (x < 0){
        return "";
    }else{
        return x + ", " + backwards(x - 1);
    }
}

I made a method that if given a positive integer(through command line), will count from that integer all the way to 0. My question is what approach should I take to reverse this?

For example, instead of going

4, 3, 2, 1, 0,

I want it to be like so

0, 1, 2, 3, 4
like image 820
Xirol Avatar asked Dec 06 '25 07:12

Xirol


2 Answers

Just reverse the return statement, so that it produces the output from 0 to x - 1 before it outputs x.

public static String backwards(Integer x) {
    if (x < 0) {
        return "";
    } else {
        return backwards(x - 1) + ", " + x;
    }
}
like image 131
Eran Avatar answered Dec 08 '25 19:12

Eran


A slightly modified version to avoid a the result starting with a ",". The condition could have been "x == 0" but using "<=" avoids an extra check for a negative input value of X.

public static String backwards(Integer x){
    if (x <= 0){
        return "0";
    }else{
        return backwards(x - 1) + ", " + x;
    }
}
like image 42
Dragos.Cojocari Avatar answered Dec 08 '25 20:12

Dragos.Cojocari