Recursion - digits in reverse order

前端 未结 15 1070
一向
一向 2021-01-15 10:32

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

15条回答
  •  南笙
    南笙 (楼主)
    2021-01-15 10:50

       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.

提交回复
热议问题