Recursive functions work by breaking the problem into smaller parts. It looks like you're trying to break the problem into smaller parts by dividing it by 2. That can work, but you have to keep two things in mind:
You have to count the bits in both parts. For example, if you call bitCount(val/2)
, that's fine: you've just called bitCount()
on a smaller problem, on all but the last bit of val
. But what about the last bit that you just threw away? You have to count it if it's 1. (Hint: val%2
).
You can't make recursive calls forever. In this case: if val
is less than 2, then val/2
will be 0, so there are no 1 bits in it, so there's no need to call bitCount(val/2)
to discover that. So you need to "break the recursion" by not calling bitCount
in that case.
As I said, this can work, but it's not a particularly good example of a recursive function, because the "breaking it into smaller parts" piece is pretty lopsided. This algorithm will make as many recursive calls as there are bits in the number; it ends up having roughly the same time complexity ("big O") as a straightforward, linear algorithm. Ideally you'd break the number into two halves based on the number of bits, not based on the number.
In other words, in your example, 94 in binary is 1011110
, and you're breaking it into the two subproblems 101111
and 0
. It'd be better to break it into, say, 1011
and 110
.
I don't know of an easy way to do that; splitting a number in half that way is probably about as hard as counting bits in the first place, so there's little advantage. Another possibility is to break off, say, the bottom 4 bits each time, by calling bitCount(val/16)
(equivalently, bitCount(val>>4)
).