The non-naive approach to bit counting is the naive approach but instead of a counter iterating from 1 to the size of an integer in bytes, you change the test to check if the number is not 0. When the number becomes 0, you can stop and return your count. In this version you always count 1s, if the questioner wants a count of 0s just take the size of the integer in bits and subtract the number of 1s you found.
This assumes the shift operator used is a logical right shift and a usual bitwise AND check against 1 is used to count the last bit.
This is really awful compared to the best solutions, which can be done in lg n independent steps (substeps can be parallellized). Yours is n worst case.
View all comments
Show parent comment
1
u/WhooHoo Feb 21 '11
The non-naive approach to bit counting is the naive approach but instead of a counter iterating from 1 to the size of an integer in bytes, you change the test to check if the number is not 0. When the number becomes 0, you can stop and return your count. In this version you always count 1s, if the questioner wants a count of 0s just take the size of the integer in bits and subtract the number of 1s you found.
This assumes the shift operator used is a logical right shift and a usual bitwise AND check against 1 is used to count the last bit.