I have to make a recursive function that finds the number of ones from 0 to n recursively.
So f(16) = 9
(1,10,11,12,13,14,15,16)
This is obviously homework so I would appreciated if you did NOT post any code, just the reasoning behind it.
What I’ve reasoned so far is that if you do %10 of a number it will tell you if the least significant is a one, also if you do an integer division by 10 you lose that digit.
So I’m guessing the approach will be can be checking if number%10 == 1 and then calling the function with f(n/10), but then I get lost in the actual implementation.
I would appreciate if you could comment what approach would you use, it has to be recursive just because it’s home work, the procedural approach was trivial.
You’ve got two parts to your problem.
Part one first:
If the right-most digit is 1, then
number % 10 == 1.If the number is > 9 you need to check other digits, you can do this by doing the same test on the number after integer-divide 10. If the number <= 9, then that would give you zero.
So your OnesInNumber function is a bit like:
number / 10.number % 10 == 1add 1 to that result.This will for example, give you
1when called on10,1,12,303212, give you2when called on11, and so on.Your OnesInZeroUntil function is then like:
number - 1.OnesInNumber(number)to this.So you’ve a recursive function that works out the number of
1in a number, and another recursive function that works out the number of1in every number up to that one, building on that first function.That’d be enough to write a quick 2 functions in, had you not requested that we don’t.
(Tip: If your teacher isn’t already requiring it, see if you can work out how to do this without recursion. Every recursive function can be re-written as a non-recursive form, and it’s a practical skill to be able to do that some people teaching recursion don’t seem to cover).