Hello All,
I am asked to create a recursion function that will tell how many ones are in the binary representation of the variable N. So if a user input 4 it would tell them there are one ones. It also says use the fact that this is equal to the number of ones in the representation of N/2 + 1, if N is odd.
Perhaps a point in the right direction would be helpful, I understand the theoretic concept just coding it is my trouble.
Hint: use a mask = 1 ; iterate through each bit using a for loop (int i = 0 ; i < sizeof(int)*8 -1 ; i++)
{
if(number&(mask<<i))
//bit is one
else
//bit is zero
}
Edit : oh i see you need recursion then implement the above loop using a recursive function.
This code returns the sum of the least significant bit and the remainder of the bits recursively until no more bits are set.
So if the number being tested is 10 decimal (1010 binary), then the call will go something like this:
countBits(10) = countBits(5) = 1 + countBits(2) = 1 + countBits(1) = 1 + 1 = 2.
It's important that the number be unsigned so that the top bit does not propagate indefinitely.