Given an integer, count how many of its binary bits are set to 1 (its "Hamming weight").
Example
Input: 11 (binary 1011)
Output: 3
Approach
Repeatedly check the lowest bit with n & 1, add it to a running count, then right-shift n by one bit to check the next one. Stop once n becomes 0. This runs in O(number of bits) time — for a 32-bit integer, at most 32 iterations.
Walkthrough
python
1count = 0
2while n:
3 count += n & 1
4 n >>= 1
5print(count)
Step 1 / 4
11 in binary is 1011. Its lowest bit (11 & 1) is 1 — count becomes 1, then shift right to check the next bit.
Input format
Line 1: a single non-negative integer n
Print the number of set bits.
Not solved yet
Ctrl+Enter
Editor
Input (stdin)
Output
Run your code to see output here.
Isolated sandbox · not executed on your devicePowered by Judge0 CE (free, self-hosted). Runs in an isolated sandbox — not on your device.
Editor
Input (stdin)
Output
Run your code to see output here.
Isolated sandbox · not executed on your devicePowered by Judge0 CE (free, self-hosted). Runs in an isolated sandbox — not on your device.