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:13 | ISBN:9780136091813 | Edition: 2

Question

Write a recursive method called evenDigits that accepts an integer parameter and that returns the integer formed by removing the odd digits from it. For example, evenDigits(8342116) returns 8426 and evenDigits(-34512) returns 42. If the number is 0 or has no even digits, such as 35159 or 7, return 0. Leading zeros in the result should be ignored.

TextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbook

Answer

package recursion;

public class EvenDigits {

	public static long evenDigits(long value) {

        // if the argument is equals 0 return 0
		if (value == 0)
			return 0;

        // get the last digit using module operator
		long lastDigit = value % 10;

        // if the last digit is even make recursive call and add last digit
		if (lastDigit % 2 == 0) {
			return 10 * evenDigits(value / 10) + lastDigit;
		} else {
			return evenDigits(value / 10);
		}

	}

	public static void main(String[] args) {
		long x = 654653132;
		System.out.print("the even digits in number " + x + " are: ");
		System.out.println(evenDigits(x));
	}

}
Output:


the even digits in number 654653132 are: 6462

 

0 0

Discussions

Post the discussion to improve the above solution.