NeetCode #853LC-191EasyBit ManipulationBlind 75NC 150NC 250
← Back to All Problems#853 · #191 · Number of 1 Bits(位 1 的个数)
📌 Problem Statement & Constraints
Write a function that takes an unsigned integer
n and returns the number of set bits in its binary representation (the Hamming weight). Constraints: 1 <= n <= 2^31 - 1, so the value fits in 32 bits.💡 Core Algorithmic Approaches
- The naive loop tests the lowest bit with
n & 1and shiftsnright until it becomes zero. - A faster variant is Brian Kernighan's trick:
n &= n - 1clears the lowest set bit, so the loop runs exactly once per set bit instead of once per bit position. - Both are correct because clearing bits never creates new ones; the loop terminates when no set bits remain.
- Python also exposes the built-in
int.bit_count, but the interview expects the manual loop.
💻 Benchmark Python3 Implementation
class Solution:
def hammingWeight(self, n: int) -> int:
count = 0
while n:
n &= n - 1 # clears the lowest set bit
count += 1
return count
# Shift-and-test variant: runs once per bit position
class Solution2:
def hammingWeight(self, n: int) -> int:
count = 0
while n:
count += n & 1
n >>= 1
return count⚡ Complexity Deep Dive
⏱️ Time Complexity
O(k) where k is the number of set bits (Kernighan); O(32) for the shift variant.
💾 Space Complexity
O(1): a single counter.
⚠️ Interview Pitfalls & Follow-ups
- Treating
nas signed: in fixed-width languages an arithmetic right shift on a negative value never reaches zero, so the loop hangs. Python's integers are unbounded, butn &= n - 1is the portable fix. - Assuming the Kernighan loop always runs 32 times: it runs once per set bit, so
n = 8finishes after one iteration. - Using
bin(n).countas the whole answer: it is idiomatic Python but skips the bit manipulation the problem is testing. - Shifting the wrong direction:
n >>= 1discards the bit just tested; shifting left would loop forever.