When dealing with recursion, its important to note down what your base and recursive cases are and go from there. These different cases will essentially become the structure of your function.
You've already figured out the different cases for your problem:
- If
n == 0
- If 8 is in the ones digit place (
n % 10 == 8
) - If 8 isn't in the ones digit place (
n % 10 != 8
)
If n == 0
, then we just return 0.
If n % 10 == 8
, then we know we have one 8, but we need to call count8
again with n / 10
as our input parameter to count8
When we return out of this call, we. When we return out of this call, we add 1 to our result before returning it since we had already found one 8. Now add 1 to our result before returning it since(the 8 we had already found one 8) to the result of the count8
call.
- In this case, you will want to check if the next digit is an 8 as well. If it is, then you will want to increment your result by 1 before you return. You can do this before or after the first recursive call. Just make sure to pass in
n / 10
after you've "removed" the back-to-back 8's.
If n % 10 != 8
, then we simply call count8
with n / 10
as our input parameter and return the result from this call.
Hopefully this paints a clearer picture in how to cleanupyou can structure your function (you can do it in 6 lines!)a clearer way.