public static int count(int number) {
if (number == 0)
return 0;
int c = 0;
if (number % 100 == 88)
c = 2;
else if (number % 10 == 8)
c = 1;
return (c + count(number / 10));
}
The key to understanding recursion is to not think too hard. I couldn't understand the concept myself until I realized - recursion just works, period!
All you need to do is to find out, how the problem can be solved by solving the same problem but with smaller input.
First of all, note how I started the algorithm. I checked to see if the number is 0. If it is, that means that previous number was 1 digit long. That means, I must stop recursively calling algorithms. So I just returned a zero.
That's how you should always start your recursive algorithms. Check for the terminating condition.
I have declared a variable 'c'. It will store a numeric count for the rightmost number.
Then I started dividing a problem into a smaller, similar problem. First, I checked the last 2 digits. If those digits are 88, that means that the number has two 8's together. So the numeric value for the rightmost digit is 2.
If previous test failed, I check to see if there's just one 8. If there is, the numeric value for it will be 1.
If not, the numeric value gets to stay at 0.
That's it! I have examined the rightmost digit. Now, all I have to do is make the problem smaller. I delete the rightmost digit, and pass the rest of the number to the same function, which will examine the rest of rightmost digits. That function will return the numeric values for the rest of numbers, I will add that number to my and will return the total.