3

It is possible to count the number of zeros in an integer through a recursive method that takes a single int parameter and returns the number of zeros the parameter has.

So:

zeroCount(1000)

Would Return:

3

You can remove the last digit from an integer by doing: "12345 / 10" = 1234

You can get the last digit from an integer by doing: "12345 % 10" = 5

This is what I have so far:

public static int zeroCount(int num)
{
    if(num % 10 == 0)
        return num;
    else
        return zeroCount(num / 10);
}

Does anyone have any suggestions or ideas for helping me solve this function?

1
  • 1
    The base case is wrong. There are many values for which x % 10 is 0. (The modulus operation should likely should be folded into the recursive case.) Commented Nov 8, 2012 at 5:23

16 Answers 16

6
public static int zeroCount(int num)
{
    if(num == 0)
       return 0;

    if(num %10 ==0)
        return 1 + zeroCount(num / 10);
    else
        return zeroCount(num/10); 
}

this would work

Sign up to request clarification or add additional context in comments.

3 Comments

Thank you very much, now I'll try counting the number of any digits on my own.
Something unexplainable happens and I'm trying to break this recursive method into separate pieces to see how it works. When the method begins and num = 1230005, then if(num / 10 != 0) is true so it moves down to the next if statement: if(num%10 == 0), and 1230005 % 10 is equal to 0.5 which is technically 0 since it's an int and not a double. But even though num % 10 (1230005%10) equals 0, it doesn't return 1 + zeroCount(num / 10), instead it goes straight to the else. What am I missing here? how does it skip "if(num%10 == 0)" when that statement is true??
@MattAndrzejczuk, I know it's been a long time since this post (over a decade), but are you using Java, or Javascript? The tags for the question indicate Java. Your statement that "1230005 % 10 is equal to 0.5 which is technically 0 since it's an int and not a double" makes me think you're thinking about Javascript. Remember, Javascript isn't strongly typed like Java. Your numbers are being treated as floating precision in Javascript. See here: stackoverflow.com/a/3966511
5

Run through your code in your head:

zeroCount(1000)

1000 % 10 == 0, so you're going to return 1000. That doesn't make sense.


Just pop off each digit and repeat:

It sounds like homework, so I'll leave the actual code to you, but it can be done as:

zeroes(0) = 1
zeroes(x) = ((x % 10 == 0) ? 1 : 0) + zeroes(x / 10)

Note that without the terminating condition, it can recurse forever.

Comments

1

There are three conditions here:
1. If number is single digit and 0 , then return 1
2. If number is less than 10 i.e. it is a number 1,2,3...9 then return 0
3. call recursion for zeros(number/10) + zeros(n%10)

zeros(number){
  if(number == 0 ) //return 1
  if(number < 10) //return 0
  else
       zeros(number/10) + zeros(number%10)
}

n/10 will give us the n-1 digits from left and n%10 gets us the single digit. Hope this helps!

Comments

1

Check this out for positive integers:

 public static int zeroCount(int number) {
    if (number == 0) {
      return 1;
    } else if (number <= 9) {
      return 0;
    } else {
      return ((number % 10 == 0) ? 1 : 0) + zeroCount(number / 10);
    }
  }

Comments

0

it is a simple problem and you don't need to go for recursion I think a better way would be converting the integer to a string and check for char '0'

public static int zeroCount(int num)
{
String s=Integer.toString(num);
int count=0;
int i=0;
for(i=0;i<s.length;i++)
{
if(s.charAt(i)=='0')
{
count++;
}
}
return count;
}

Comments

0

You have to invoke your recursive function from both if and else. Also, you were missing a Base Case: -

public static int zeroCount(int num)
{
    if(num % 10 == 0)
        return 1 + zeroCount(num / 10);
    else if (num / 10 == 0)
        return 0;
    else
        return zeroCount(num / 10);
}

8 Comments

There is no base case here. Infinite recursion!
This will result in an StackOverflowException. The exit criteria is missing. (The OP can find a solution for that, just to let him know ;) )
@Andreas_D.. Yeah I quoted that in the last line. :)
@BhavikShah.. Yeah is it? And I'm not here to give exact code to OP. He'll figure out himself. I have just pointed that he need to call his methods from both if and else.
Hey guys this is not facebook
|
0
import java.util.*;
public class Count
{
static int count=0;
static int zeroCount(int num)
{
  if (num == 0){
     return 1;
  }
  else if(Math.abs(num) <= 9)
  { 
     return 0;
  } 
  else
  {
     if (num % 10 == 0)
     { // if the num last digit is zero
        count++;
       zeroCount(num/10);
     } // count the zero, take num last digit out
     else if (num%10 !=0){
         zeroCount(num/10);
     }
  }
  return count;
  }

    public static void main(String[] args)
 {
  Scanner sc = new Scanner(System.in);
  System.out.print("Input: ");
  int num = sc.nextInt();
  System.out.println("Output: " +zeroCount(num));
  }  
  }

Comments

0
public static int count_zeros(int n)
{
    if(n<=9)
    {
        if(n==0)
        {  
            return 1;
        }
        else
        {
            return 0;
        }
    }

    int s=n%10;

    int count=0;

    if(s==0)
    {
        count=1;
    }

    return count+count_zeros(n/10);
}

Comments

0
 int countZeros(int n){
     //We are taking care of base case 
if(n<=9){         
    if(n==0){
         return 1;
    }
 else
 {
     return 0;
 } 
}     
   int last=n%10;  //last element of number for e.g- 20403, then last will give 3
   int count=0;    //Initalsizing count as zero
   if(last==0){    //We are checking either the last digit is zero or not if it will 
        will update count from 0 to 1
     count=1;
  }
    return count+countZeros(n/10);  //Recursive call 
   } 

1 Comment

Major issue is on the base case we have here indented base case to count number 0 as one 1 no. of zeros, if we keep only either n==0 or n==1 as the base case then in case of n==0 the number 0 will be considered as 0 no. of zeros which is wrong also if we keep n==1 then it will add 1 extra while returning count
0
int check(int n){
    if(n==0)
        return 1;
    return 0;

}


int fun(int n)
{
    if(n/10==0)
    {
        if(n==0){
            return 1;
        }
        else{
                return 0;
    }
    }
    return check(n%10)+fun(n/10);

}

Comments

0

Check this out, this is the solution I came up with.

int countZeros(int input){
//base case
if(input == 0){
    return 1;
}

int count = 0;
int lastDigit = input%10;
if(lastDigit == 0){
  count = 1;
}

//calc the smallInput for recursion
int smallInput = input/10;
//set smallAns = 0, if i/p itself is not 0 and no 0 is present then return smallAns = 0
int smallAns = 0;
//recursion call
if(smallInput != 0){
    smallAns = countZerosRec(smallInput);            
}

//if we get lastDigit = 0 then return smallAns + 1 or smallAns + count, else return smallAns  
if(lastDigit == 0){
    return smallAns+count;
}
else{
    return smallAns;
}}

1 Comment

You might want to explain your solution.
0

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)
{
  if(num == 0) return 1;      
  else if(Math.abs(num) < 9)  return 0;
  else return (num % 10 == 0) ? 1 + zeroCount(num/10) : zeroCount(num/10);
}

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

Comments

0
static int cnt=0;
    public static int countZerosRec(int input) {
        // Write your code here
        if (input == 0) {
            return 1;
        }      
        if (input % 10 == 0) {
            cnt++;           
        }
        countZerosRec(input / 10);                  
        return  cnt;
    }

Comments

0

CPP Code using recursion:

int final=0;
int countZeros(int n)
{
    if(n==0) //base case
    return 1;
    int firstn=n/10;
    int last=n%10;
    int smallop=countZeros(firstn);
    if(last==0)
        final=smallop+1;
    return final;
}

1 Comment

Hi @UjjwalKarnanl - just wondering what this really adds over the 2 top answers (from 2015 mind you) to the OP question? [infact if you look at them you might see that the code is more complicated than it needs to be !!].
0
int countZeros(int n) 
{
if(n==0)
{
    return 1;
}
if(n<10) // Needs to be java.lang.Math.abs(n)<10 instead of n<10 to support negative int values
{
    return 0;
}
int ans = countZeros(n/10);
if(n%10 == 0)
{
    ans++;
} 
return ans;
}

1 Comment

Hello. Notice this algorithm does not support negative integers.
0

public static int countZerosRec(int input){ // Write your code here

    if(input == 0)
        return 1;
    
    if(input <= 9)
        return 0;
    
    if(input%10 == 0)
        return 1 + countZerosRec(input/10);
    
    return countZerosRec(input/10);
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.