Number of 1 Bits
Given a positive integer n, return the number of set bits (1s) in its binary representation. Repeatedly apply n & (n - 1) , which clears the lowest set bit in one step. Count how many times that takes until n reaches 0.
Constraints
- 1 ≤ n ≤ 231 - 1
Example
Input
n = 11 (binary 1011)Output
3Explanation Binary 1011 has three 1 bits.
In plain terms
- Set bit
- A bit in the binary representation of a number whose value is 1.
- n & (n - 1)
- Subtracting 1 from n flips the lowest set bit to 0 and every bit below it to 1; AND-ing with n then turns off exactly that lowest set bit and leaves everything above it untouched — one of the handful of bit tricks worth memorizing.
Clear the lowest set bit until n reaches 0
81
40
21
11
Statusinit
n = 1011 (11). Lowest set bit is at position 0.
What happens in this step
n = 00001011 (11) Three bits are set, at positions 0, 1, and 3. Each round below clears the lowest set bit using n & (n - 1) and counts it.
Step 1 of 4
Steps to visualize
- Start a bit count at 0.
- While n is not 0, compute n & (n - 1) — this clears the lowest set bit.
- Add one to the count each time a bit is cleared.
- Stop once n reaches 0; the count is the number of set bits.
Walk through the code
Same walkthrough, now with the code. Press Next to move one step and watch which lines run.
81
40
21
11
Statusinit
n = 1011 (11). Lowest set bit is at position 0.
What happens in this step
n = 00001011 (11) Three bits are set, at positions 0, 1, and 3. Each round below clears the lowest set bit using n & (n - 1) and counts it.
Step 1 of 4
Solution
function hammingWeight(n) {
let count = 0;
while (n !== 0) {
n &= n - 1;
count++;
}
return count;
}- Time
- O(k), k = number of set bits
- Space
- O(1)
Test cases
| Input | Expected | Covers |
|---|---|---|
n = 11 | 3 | example from the docstring |
n = 128 | 1 | a power of two has exactly one set bit |
n = 255 | 8 | every bit set within a byte |
n = 1 | 1 | smallest valid input |
n = 2147483645 | 30 | a large value near the upper bound of a 32-bit signed integer |
n = 7 | 3 | consecutive low bits all set |