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.
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