Java递归和整数两位数 [英] Java recursion and integer double digit

查看:135
本文介绍了Java递归和整数两位数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将整数作为参数,然后使用递归来加倍整数中的每个数字。

I'm trying to take an integer as a parameter and then use recursion to double each digit in the integer.

例如 doubleDigit (3487)将返回 33448877

我被困了,因为我无法弄清楚如何读取数字中的每个数字。

I'm stuck because I can't figure out how I would read each number in the digit I guess.

推荐答案

要使用递归执行此操作,请使用模数运算符(%),每次除以10并向后累积结果字符串,直到你到达基本情况(0),没有什么可以分开。在基本情况下,您只返回一个空字符串。

To do this using recursion, use the modulus operator (%), dividing by 10 each time and accumulating your resulting string backwards, until you reach the base case (0), where there's nothing left to divide by. In the base case, you just return an empty string.

String doubleDigit(Integer digit) {

      if (digit == 0) {
        return "";
      } else {
        Integer thisDigit = digit % 10;
        Integer remainingDigits = (digit - thisDigit) / 10;
        return doubleDigit(remainingDigits) + thisDigit.toString() + thisDigit.toString();
      }
    }

这篇关于Java递归和整数两位数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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