Reputation: 77
My code is counting the wrong number of zeroes in a read in text file and I'm not sure how to fix it. Random numbers are coming up either one more than what i need or not reading at all. Can anyone help?
private static int count0(int n, boolean zero) {
if (n <= 0)
return 0;
else if (n % 10 == 0)
return 1 + (zero ? 1 : 0) + count0(n / 10, true);
else
return count0(n / 10, false);
}
public static int count0(int n) {
return count0(n, false);
}
enter code here
Upvotes: 1
Views: 113
Reputation:
Getting rid of 'zero', we have
n is 0 --> count 0
otherwise add 1 if this digit is zero, and
count the zero digits to the left
private static int count0(int n) {
if (n <= 0)
return 0;
else
return (n % 10 == 0 ? 1 :0) + count0(n / 10);
}
This works for (say) original n = 10 but IMO does not work for original n = 0; the answer should surely be 1? That is, 0 is a special case. Both '10' and '0' have one zero.
Upvotes: 1