I need to implement a recursive method printDigits that takes an integer num as a parameter and prints its digits in reverse order, one digit per line.
This is what
public class reverseIntRec{
public static void main(String args[]) {
System.out.println(reverse(91));
}
public static int reverse(int x) {
String strX = String.valueOf(x);
if (Math.abs(x) < 10)
return x;
else
return x % 10 * ((int) Math.pow(10, strX.length()-1)) + reverse(x/10);
}
}
Here is my answer return as integer. I converted x
into string to see how many 0s
you should multiply with.
For example: reverse(91) returns 1 * 10 + reverse (9), and that returns 10 + 9 = 19.