Reputation: 63
I'm having trouble writing a recursive method that is meant to remove any odd digits from an int - for example: evenDigits(123456)
should return 246
. My first thought was to turn the int into a string and cycle through that way but the question explicitly states you cannot use Strings to solve it.
Any help is appreciated
EDIT: This is what I have so far, I'm not sure if its along the right lines, but I cannot figure out what to do if the last digit was to be even
public static int evenDigits(int n)
if(n==2)
{
return 2;
}
if(n==1)
{
return 0;
}
if((n%10)%2==1) //if the last digit is odd
{
return evenDigits(n/10); //run it again without the last digit
}
Upvotes: 1
Views: 1792
Reputation: 42461
Since its obviously the homework, I can't provide a full solution, however here are some hints:
When you define recursion you should think when you stop (a stop condition). If you follow the hints provided by @marksplace - then you will probably stop when the recursion will reach the point where no digits have left.
Another thing you should think of is where to store the result "accumulated so far". You'll pass it through the recursion. Its even called "accumulator" in the literature. So when you reach the stop condition you'll return the accumulator. In addition think about how exactly you are going to update the accumulator.
Here is an example of how it can work without diving into the code:
....
At last - stop when you reach the point, where there are no digits, accumulator will contain the answer
Good luck!
Upvotes: 3