简体   繁体   中英

Using recursion how can I count number of bits in an unsigned integer?

Why this code terminated and crashed to evaluate the number of bits?

int main(void)
{
    int y = 94;
    int m  = bitCount(y);


    printf("%d",m);
    return 0;
}

int bitCount(int val)
{
    int i = 0;
    if(!bitCount(val/2))
        i++;
    return i;
}

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:

  1. 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 ).

  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) ).

I did a simple program where you can count a number of bits, I will assume you were talking about the 1s and 0s. If not, well I'm dumb :P

bitCount function using recursion:

int bitCount(unsigned int x, int count) {       
    if (n==0) return count;
    if (n%2==1) bitCount(n/2,count+1);
    else bitCount(n/2,count);
}

Calling the fuction on main:

int main() {
   unsigned int x=94;
   int counting = 0;
   printf ("Result of bits: %d \n", bitCount(x,counting));

return 1;
}

With the unsigned int = 94, it will return 5. I hope it was that you wanted :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM