191. Number of 1 Bits
Easy NeetCode 150 ↗ Open on LeetCode Source: NeetCode 150
Quick review
- Pattern
- Bit Manipulation
- Time
- O(1)
- Space
- O(1)
Standard Solution (C++)
SummaryCount the number of bits set to 1 (the Hamming weight) in a 32-bit integer by repeatedly clearing the lowest set bit until the value reaches zero.
Approach
- Use Brian Kernighan's bit trick:
bits &= bits - 1clears the lowest set bit inbitseach iteration, so the loop runs exactly as many times as there are 1-bits. - Cast
ntouint32_tbefore operating to avoid undefined behavior from signed-integer overflow whennisINT_MIN(n - 1would overflow a signedint). - This is faster in practice than shifting through all 32 positions because it skips over zero-bit gaps entirely.
- The loop terminates when
bitsbecomes 0, at which point all set bits have been counted. - Since
bitsis a 32-bit value, the loop executes at most 32 times, giving O(1) time.
#include <cstdint>
using namespace std;
class Solution {
public:
int hammingWeight(int n) {
int count = 0;
uint32_t bits = static_cast<uint32_t>(n); // avoid signed overflow UB
// Each iteration clears the lowest set bit; loop runs once per set bit.
while (bits) {
bits &= bits - 1; // drop the rightmost 1-bit
++count;
}
return count;
}
};
Time O(1) — at most 32 iterations for a 32-bit integer Space O(1)
A canonical reference solution. Problem statement © LeetCode — see the official link above.
My Solution (C++)
class Solution {
public:
int hammingWeight(int n) {
int count=0;
while(n>0){
if(n&1>0){
++count;
}
n>>=1;
}
return count;
}
};
// Time Complexity: O(1), since the number of 1 bits is at most 32.
// Space Complexity: O(1) Time O(1) Space O(1)
My own solution and notes, as I wrote them.
▶ Run it — editable in-browser playground with a sample driver C++
Your solution plus an auto-generated main() and sample input so Run produces output. The driver and inputs are unverified — edit freely; Reset restores this starting point.
C++ ▶ Runnable Auto-generated driver with sample input — unverified.
Runs in a free public sandbox (Wandbox). Output and timing include network latency; don't paste secrets.