SHARE
SPREAD
HELP

The Tradition of Sharing

Help your friends and juniors by posting answers to the questions that you know. Also post questions that are not available.


To start with, Sr2Jr’s first step is to reduce the expenses related to education. To achieve this goal Sr2Jr organized the textbook’s question and answers. Sr2Jr is community based and need your support to fill the question and answers. The question and answers posted will be available free of cost to all.

 

#
Authors:
Stuart Reges, Marty Stepp
Chapter:
Recursion
Exercise:
Exercises
Question:4 | ISBN:9780136091813 | Edition: 2

Question

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.

TextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbook

Answer

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

 

0 0

Discussions

Post the discussion to improve the above solution.