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
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;
}
}
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;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With