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)
keep array like this...which is direct mapping of how many ones are there in nos 0-255...
int [] oneCount = {0,1,1,2,1..........8}
for each 8 bit segment of input number...lookup this array and sum result...
constant time...
return oneCount[no & 0xff] + oneCount[(no & 0xff00)>>8] + oneCount[(no & 0xff0000)>>16]+ oneCount[(no & 0xff000000)>>24]
Divide the number by 2.. and count the number of remainders which are 1. until the number becomes 1, then consider 1 divided by 2 as 1.
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment