Dec 27, 2008

Give a very good method to count the number of ones in a "n" (e.g. 32) bit number.(in lg(n) or constant time if possible)

Give a very good method to count the number of ones in a "n" (e.g. 32) bit number.(in lg(n) or constant time if possible)

Besides /2 or >>1 methods
{{{
int arr[256];//record how many 1 bits for each number from 0 to 255
return arr[num&0xff]+arr[num>>8&0xff]+arr[num>>16&0xff]+ar[num>>24&0xff];
}}}
{{{
int c=0;
while(num>0)
{
num=num&num-1;
c++;
}
}}}

No comments:

Post a Comment