) Sample implementation that counts total number of set bits using recursion is given below could
be:
unsigned int number_of_ones(unsigned int n)
{
if(n&1==1) {
return 1+number_of_ones(n-1);
}
else {
retrun number_of_ones(n/2);
}
}
Using loops this can be accomplished as below (Note: The solution below doesn’t loop over the
whole 32 bits, usually, of an unsigned integer)
unsigned int bitcount(unsigned int x)
{
unsigned int count;
for(count = 0; x; x &= (x-1)) count++;
return count;
}
You can also use a lookup table to count the number of set bits.
be:
unsigned int number_of_ones(unsigned int n)
{
if(n&1==1) {
return 1+number_of_ones(n-1);
}
else {
retrun number_of_ones(n/2);
}
}
Using loops this can be accomplished as below (Note: The solution below doesn’t loop over the
whole 32 bits, usually, of an unsigned integer)
unsigned int bitcount(unsigned int x)
{
unsigned int count;
for(count = 0; x; x &= (x-1)) count++;
return count;
}
You can also use a lookup table to count the number of set bits.
Comments
Post a Comment
https://gengwg.blogspot.com/