</>

191. Number of 1 Bits

Easy NeetCode 150
Bit Manipulation Time O(1) Space O(1)
↗ 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 - 1 clears the lowest set bit in bits each iteration, so the loop runs exactly as many times as there are 1-bits.
  • Cast n to uint32_t before operating to avoid undefined behavior from signed-integer overflow when n is INT_MIN (n - 1 would overflow a signed int).
  • This is faster in practice than shifting through all 32 positions because it skips over zero-bit gaps entirely.
  • The loop terminates when bits becomes 0, at which point all set bits have been counted.
  • Since bits is 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.

Related — same pattern