Matt Andrzejczuk
Matt Andrzejczuk

Reputation: 2066

How could I use a recursive method with an int parameter to return the number of zero digits in that int?

the method is:

public static zeroCount(int num)

My instructor requires this method to have one int parameter and the recursive method must return the number of zeros in num.

So zeroCount(10200) = 3, and zeroCount(100300) = 4 etc...

I could easily do this but since I'm required to use a recursive method so I am completely lost.

Upvotes: 0

Views: 1215

Answers (4)

Dio
Dio

Reputation: 704

Try the following:

public int count0(int n) {
  if(n == 0) 
     return 0;
  if(n % 10 == 0) 
     return 1 + count0(n/10);

  return count0(n/10);
} 

Upvotes: 0

dreamcrash
dreamcrash

Reputation: 51413

You know that x % 10 gives you the last digit of x, so you can use that to identify the zeros. Furthermore, after checking if a particular digit is zero you want to take that digit out, how? divide by 10.

public static int zeroCount(int num)
{
  int count = 0;

  if(num == 0) return 1;                  // stop case zeroCount(0)
  else if(Math.abs(num)  < 9)  return 0;  // stop case digit between 1..9 or -9..-1
  else
  {
   if (num % 10 == 0) // if the num last digit is zero
       count++; // count the zero, take num last digit out

   return count + zeroCount(num/10); // take num last digit out, and apply 
  } // the method recursively to the remaining digits 
}

I use math.Abs to allow negative numbers, you have to import java.lang.Math;

Upvotes: 0

Makoto
Makoto

Reputation: 106410

If you can approach the problem iteratively (that is, with some kind of loop), then you can do it recursively.

The two things you'll need when writing the recursive method are:

  • A base case; what you do when you have exhausted all digits of your number, and
  • An iterative case; what you do when you still have more digits to go.

I also notice that you don't specify the return value of your method; ideally, it would be int. Let that be a hint to you.

Upvotes: 0

Kiwi
Kiwi

Reputation: 136

Hint: What if you keep dividing the number by 10 at each recursive step and return 1 if there is no remainder and 0 if there is?

Upvotes: 2

Related Questions