Consider the number 152357 as a list of digits: 1, 5, 2, 3, 5, 7.
You can check to see whether the end of the list is a five or not. In this case, it is not. Hence, we'll add zero to the result and
recurse on what remains of the list: 1, 5, 2, 3, 5.
Now the end of the list
is a five, so we'll add one to the result and recurse on what remains: 1, 5, 2, 3.
Continue for the remainder of the list, adding one if the end of the list is a five and zero if the end is not a five.
When there is no more list, we'll simply return zero -- stopping the recursion.
What essentially happens is your list:
becomes a series of additions:
0 + 0 + 1 + 0 + 0 + 1 + 0 |
The recursion is seen in how we process the list: Another way of writing it is:
((((((( ) 1) 5) 2) 3) 5) 7) |
which becomes:
(((((((0)+0)+1)+0)+0)+1)+0) |
The problem you are having is figuring out how to convert "is the end of the list a five" into a one or a zero.
The "modulo" or "remainder" operator returns what is left over after a division. Remember in elementary school math you wrote "4 ÷ 5 = 0 R 4". In C++ that's
4 / 5 == 0
and
4 % 5 == 4
.
You don't want to add the remainder of your division to the function. You would get:
0 + 1 + 0 + 2 + 3 + 0 + 7 --> 13, and that is definitely
not the number of fives in the number.
Remember, to turn any number into a list, use
n % 10
to see what the one's place is (the end of your list) and use
n / 10
to get the remainder of the list. You know when you are out of list when the
n
is zero.
Hope this helps.