Reputation: 35
This is what I have been able to come up with so far.
public static int evens(int n)
{
String num = "" + n;
if (n>1) {
if (n%2 == 0) {
return n + evens(n%10);
}
else {
int len = num.length();
num = num.substring(0, len-1);
n = Integer.parseInt(num);
return n + evens(n%10);
}
}
else {
return n;
}
}
My logic is to make the integer a string, then divide by 10 each time to make the next digit (right to left) in the ones place (and using integers the previous digit should be dropped I believe). Then I am trying to use %2 to find the remainder, and if it is not ==0 the digit in the ones place is odd, and to somehow eliminate that digit from the string (by taking the length then taking a substring from 0 to len-1). I think my problems include possibly logic, obviously something is wrong with my syntax, and the first line of the method defining the string causes it to redefine through every recursion, messing it up.
Upvotes: 1
Views: 153
Reputation: 53535
Indeed, there are a few bugs that are mainly caused by redundant logic, but it can easily get (simplified and) fixed:
public static String evenDigits(int n)
{
if (n > 0) {
if (n % 2 == 0) {
return n % 10 + "" + evenDigits(n / 10);
} else {
return evenDigits(n / 10) + "";
}
} else {
return "";
}
}
Pay special attention to the "switch" of the parameters in the return statement from:
return n + evenDigits(n%10);
to:
return n % 10 + "" + evenDigits(n / 10);
by returning n % 10
you'll return the current digit you're working on (which is what you want) and send the "rest" of the number recursively by using n / 10
.
A different approach can be, to not use Strings at all. Combining it with an iterative approach (vs. the recursive one that was suggested above) the result is something like the following:
public static int evenDigits(int n) {
int res = 0;
int mag = 0;
while (n > 9) {
int digit = n % 10;
n /= 10;
if (digit % 2 == 0) {
res += Math.pow(10, mag) * digit;
mag++;
}
}
return res;
}
Upvotes: 1
Reputation: 159114
Compact non-string version:
public static int evenDigits(int n) {
return (n&1) != 0 ? evenDigits1(n/10) : n < 10 ? n : n%10 + evenDigits(n/10)*10;
}
Explained:
public static int evenDigits(int n) {
if ((n & 1) != 0) {
// Last digit is odd, so remove it. Recurse on higher digits
return evenDigits(n / 10);
}
if (n < 10) {
// Single digit number is even, so we're done
return n;
}
// Keep last digit (it is even). Recurse on higher digits
return n % 10 + evenDigits(n / 10) * 10;
}
Upvotes: 1