Write a recursive method called doubleDigits that accepts an integer n as a parameter and returns the integer obtained by replacing every digit of n with two of that digit. For example, doubleDigits(348) should return 334488. The call doubleDigits(0) should return 0. Calling doubleDigits on a negative number should return the negation of calling doubleDigits on the corresponding positive number; for example, doubleDigits(–789) should return –778899.
package recursion;
public class DoubleDigits {
// this method takes int value as argument
public static String doubleDigits(int value) {
// check if the value is greater than zero
if (value > 0)
return doubleDigitHelper(value);
else if (value < 0) {
System.out.print("-");
return doubleDigitHelper(Math.abs(value));
} else
return "0";
}
public static String doubleDigitHelper(int value) {
if (value == 0) {
return "";
} else {
// get last digit by using module operator
Integer lastDigit = value % 10;
Integer digits = (value - lastDigit) / 10;
return doubleDigitHelper(digits) + lastDigit.toString() + lastDigit.toString();
}
}
// driver method
public static void main(String[] args) {
System.out.println(doubleDigits(45454));
}
}
Output:
4455445544