Recursion - digits in reverse order

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

    I came looking for a more elegant version than mine, but perhaps this just requires a bit of a messy algorithm. Mine also returns the actual integer value which I agree is much more useful than only printing the string: Mine:

    public static int reverse(int n){
            if(n<10)return n;
            return  n%10*(int)Math.pow(10,(int)Math.log10((double)n)) + reverse(n/10);
        } 
    

    so this returns the last digit, multiplied by 10^current power + (recursive call)

提交回复
热议问题