codejump
EasyPythonJavaScriptTypeScript

Bits — Number of 1 Bits

AlgorithmsBit Manipulation

solve(n) — n is an integer with 0 <= n < 2^31. Return the number of 1 bits in
its binary representation (its Hamming weight).

Looping over all 31 bits works. Brian Kernighan's trick is faster: n & (n - 1)
clears the lowest set bit, so the loop runs once per 1 bit instead of once per bit.

Examples

solve(11)          → 3      // 1011
solve(128)         → 1      // 10000000
solve(2147483647)  → 31

Sample tests

Test #11011
Input: [11]
Output: 3
Test #2A power of two
Input: [128]
Output: 1
Test #3Zero
Input: [0]
Output: 0