Blind 75 · #71 · Bit Manipulation

Number of 1 Bits

EasyBit tricksTime O(set bits)Space O(1)

Number of 1 Bits is an easy Bit Manipulation problem from the Blind 75. The key pattern is bit tricks, and a good solution runs in O(set bits) time.

Problem

Treat the input as an unsigned 32-bit integer and return its number of set bits.

Examples

Example 1

Input

29

Output

4

Example 2

Input

22

Output

3

Example 3

Input

256

Output

1

Approach

n & (n − 1) clears the lowest set bit, so count how many times you can do it before n reaches 0.

PatternBit tricks
TimeO(set bits)
SpaceO(1)

Watch out for

Treat the input as unsigned 32-bit; in JavaScript use >>> rather than >>.

More Bit Manipulation problems