Search

Google
 

Saturday, July 14, 2007

Find the number of bits set in a number

Given an integer n find the number of bits set to 1 in the number.
Solution.
1. Split the integer into 4 bit blocks. (n & 0xf << i) where i = 1to 8
2. Pre - populate and array of size 16 whcih represent the number of bit set for the number 1-15.
3. get the number of bits set in each of the 8 blocks and add them up :).

No comments: