A faster approach: repeatedly flip the rightmost 1 bit to 0 until becomes 0. The number of flips equals the number of 1 bits.
The operation flips the rightmost 1 bit to 0. Why? Subtracting 1 flips all trailing bits up to and including the rightmost 1. ANDing with zeros out that rightmost 1. For example, .
Loop: while , do and increment a counter. When reaches 0, all 1s have been flipped. This runs in where is the number of 1 bits, not .