Number of 1 Bits – Solution & Complexity
Solution Walkthrough
Step 1: Clear the lowest set bit with n & (n - 1)
- Subtracting
1fromnflips the lowest1bit to0and all trailing0s to1. - Bitwise ANDing
n & (n - 1)therefore clears exactly one set bit — the rightmost1. - Repeating
n = n & (n - 1)untiln == 0loops only as many times as there are set bits (Brian Kernighan's algorithm).
- Subtracting
Step 2: Optimal O(1) bit-clearing loop
- Runs in
O(k)iterations wherek <= 31is the number of set bits (O(1)time for fixed-width integers) andO(1)space.
- Runs in
Step 3: Common mistakes
- Using signed right shift
>>on negative 32-bit integers in Java/JavaScript without>>>can cause an infinite loop if the sign bit is set. - Converting to a binary string works but allocates unnecessary memory compared to
n &= n - 1.
- Using signed right shift
Part of Blind 75 · NeetCode 150 · LeetCode 150