Xirol
Xirol

Reputation: 303

Recursion Reverse

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

Upvotes: 2

Views: 59

Answers (2)

Dragos.Cojocari
Dragos.Cojocari

Reputation: 115

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;
    }
}

Upvotes: 1

Eran
Eran

Reputation: 394126

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;
    }
}

Upvotes: 8

Related Questions