Recursion - digits in reverse order

前端 未结 15 1057
一向
一向 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:36

    I found I had to pick off the highest digit (on the left) and work towards the rightmost digit. I couldn't get a recursive one to work going from right to left.

    public static int reverseItRecursive(int number)
    {
        if (number == 0)
            return 0;
    
        int n = number;
        int pow = 1;
    
        while (n >= 10)
        {
            n = n / 10;
            pow = pow * 10;
        }
        return (n + reverseItRecursive(number - n*pow)*10);
    }
    

提交回复
热议问题