Recursion - digits in reverse order

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

    public static int reversDigits(int num) {
        if(num < 1) {
            return 0;
        }
    
        int temp = num % 10;
        num = (num - temp)/10;
        System.out.println(temp);
    
        return reversDigits(num);
    }
    

    This will print the digits one at a time in reverse order. You don't need to do System.out in your main method.

提交回复
热议问题