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?

Matt Andrzejczuk
  • 2,001
  • 9
  • 36
  • 51
  • 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.) –  Nov 08 '12 at 05:23

16 Answers16

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

Bhavik Shah
  • 5,125
  • 3
  • 23
  • 40
  • Thank you very much, now I'll try counting the number of any digits on my own. – Matt Andrzejczuk Nov 08 '12 at 14:05
  • 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?? – Matt Andrzejczuk Nov 08 '12 at 15:07
  • @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: https://stackoverflow.com/a/3966511 – Mike Christiansen Jun 26 '23 at 00:48
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.

Corbin
  • 33,060
  • 6
  • 68
  • 78
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!

Sakshi Vij
  • 41
  • 4
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);
    }
  }
Devkinandan Chauhan
  • 1,785
  • 1
  • 17
  • 42
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);
}
Rohit Jain
  • 209,639
  • 45
  • 409
  • 525
  • 2
    There is no base case here. Infinite recursion! –  Nov 08 '12 at 05:25
  • 1
    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 Dolk Nov 08 '12 at 05:26
  • @Andreas_D.. Yeah I quoted that in the last line. :) – Rohit Jain Nov 08 '12 at 05:27
  • @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. – Rohit Jain Nov 08 '12 at 05:31
  • @BhavikShah.. Your code will certainly work, but it doesn't help OP. He will just copy paste it. So, please first remove your downvote. – Rohit Jain Nov 08 '12 at 05:32
  • Ok, fine. Whoever has downvoted, here's the complete solution. I think you can learn from it. But certainly OP will not. – Rohit Jain Nov 08 '12 at 05:36
  • @BhavikShah.. Did you see the last line in my post?? I had written there, that he needs to find the Base CAse, to avoid the infinite recursion.. That he have to figure out himself. I don't think with that `quote`, he was going to be misleaded. – Rohit Jain Nov 08 '12 at 05:38
  • 1
    Hey guys this is not facebook – Shurmajee Nov 08 '12 at 05:40
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;
}
Shurmajee
  • 1,027
  • 3
  • 12
  • 35
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;

dreamcrash
  • 47,137
  • 25
  • 94
  • 117
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));
  }  
  }
Dee
  • 1
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);
}
no1spirite
  • 608
  • 12
  • 23
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 
   } 
sticky bit
  • 36,626
  • 12
  • 31
  • 42
  • 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 – Manish Kumar Feb 09 '20 at 05:56
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);

}
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;
}}
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;
    }
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;
}
  • 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 !!]. – Mr R Jun 05 '21 at 08:39
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;
}
João
  • 2,296
  • 5
  • 20
  • 30
Himanshu
  • 1
  • 1
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);
}
Adarsh
  • 1