递归 - 相反顺序的数字 [英] Recursion - digits in reverse order

查看:161
本文介绍了递归 - 相反顺序的数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要实现一个递归方法printDigits,它以整数num作为参数并以相反的顺序打印其数字,每行一位。

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 I have so far:

public class PrintDigits {

    public static void main(String[] args) {
        System.out.println("Reverse of no. is " + reversDigits(91));
    }

    /* Recursive function to reverse digits of num */
    public static int reversDigits(int number) {
        if (number == 0)
            return number;
        else {
            return number % 10;
        }
    }
}

我觉得只有我缺少一行代码,但不确定我需要做些什么来解决它。

I feel like there is only one line of code that I am missing, but not sure what I need to do to fix it.

推荐答案

public static void main(String[] args) {
    reverseDigits(98198187);
}

/* Recursive function to reverse digits of num */
public static void reverseDigits(long number) {
    if (number < 10) {
        System.out.println(number);
        return;
    }
    else {
        System.out.println(number % 10);
        reverseDigits(number/10);
    }
}

这篇关于递归 - 相反顺序的数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆