Interview Questions

Finding number of on bits (1 bits) given an integer..discuss the various approaches..what is the best one?

Microsoft Interview Questions and Answers


(Continued from previous question...)

274. Finding number of on bits (1 bits) given an integer..discuss the various approaches..what is the best one?

Question:
Finding number of on bits (1 bits) given an integer..discuss the various approaches..what is the best one?


maybe an answer:


int countbits2 (int in)
{
in = ((in >>1) & 0x55555555) + (in & 0x55555555);
in = ((in >>2) & 0x33333333) + (in & 0x33333333) ;
in = ((in >>4) & 0x0f0f0f0f) +(in & 0x0f0f0f0f);
in = ((in >>8) & 0x00ff00ff) + (in & 0x00ff00ff) ;
in = ((in >>16) & 0x0000ffff) + (in & 0x0000ffff) ;
return in;
}



maybe an answer2:


while(n!=0)
{
if(n&1)
count++;

n = n>>1;
}

(Continued on next question...)

Other Interview Questions