LET'S TALK TECHNICAL

This blog is intended to help people prepare for the job interviews and improve their analytical skills. We have posted difficult datastructures and algorithm questions and puzzles. Interview experiences section is for the people to post their interview experiences.Views expressed here are of their personal and the blog author doesn't take any responsibility for the same.

-

Followers

Jobs

Sunday, March 28, 2010

Finding number of on bits (1 bits) given an unsigned integer?

Sol 1:
Simple Iterative solution.(Very slow)

int countbits (unsigned int number) {

int count = 0;

while (number) {

count += number & 0x1u;

number >>= 1;

}

return count;

}

Sol 2:

Faster Solution for 32 bit machines.
compute 16bits then add then to return full number of ones in 32 bit number.

static char ones_in_16bit_num [0x1u << 16] ;
int countbits (unsigned int number)
{
return ones_in_16bit_num [number & 0xffffu] + ones_in_16bit_num [(number >> 16) & 0xffffu] ;

}

Popular Posts