Alex
Alex

Reputation: 63

Recursive method to remove all odd digits from an int

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

Answers (1)

Mark Bramnik
Mark Bramnik

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:

  1. 123456 a. Last digit is 6, its even, preserve it, update an accumulator (=6) b. recursive call for 12345
  2. 12345 - last digit is odd - remove it, b. recursivce call for 1234
  3. 1234 - last digit is 4 - its even, preserve it, update the accumulator 6 -> 46 (here you should think about the math formula of such an update)

....

At last - stop when you reach the point, where there are no digits, accumulator will contain the answer

Good luck!

Upvotes: 3

Related Questions