LeetCode ยท #191

Number of 1 Bits Solution

Return the number of set bits (1s) in the binary representation of an unsigned integer.

01
Section One ยท Problem

Problem Statement

๐Ÿท๏ธ

Difficulty

Easy

๐Ÿ”—

LeetCode

Problem #191

๐Ÿ—๏ธ

Pattern

Bit Manipulation โ€” Hamming weight

Example
Input: n = 11 // binary: 1011 Output: 3
02
Section Two ยท Approach 1

Shift and Mask โ€” O(32)

Check each of the 32 bits: if (n & 1) count++; n >>>= 1;. Always 32 iterations.

Java โ€” Shift & mask
class Solution { public int hammingWeight(int n) { int count = 0; for (int i = 0; i < 32; i++) { count += n & 1; n >>>= 1; } return count; } }
Python โ€” Shift & mask
class Solution: def hammingWeight(self, n: int) -> int: count = 0 while n: count += n & 1 n >>= 1 return count
03
Section Three ยท Approach 2

Brian Kernighan's Trick โ€” O(k) where k = # of 1 bits

n & (n-1) clears the lowest set bit. Count how many times until n becomes 0. Only iterates k times (number of set bits).

๐Ÿ’ก Mental model: Imagine n as a row of light switches. n-1 flips all bits from the rightmost ON switch down. AND-ing with n turns off that rightmost switch. Each operation kills exactly one light. Count the kills.
๐ŸŽฏ When to recognize this pattern: "Count set bits" or "is power of two" (check n & (n-1) == 0). Brian Kernighan's trick is faster than iterating all 32 bits when few are set.
04
Section Four ยท Trace

Visual Walkthrough

Brian Kernighan's โ€” n=11 (1011โ‚‚)
n & (n-1) clears lowest set bit. 1011 & 1010 = 1010 (count=1). 1010 & 1001 = 1000 (count=2). 1000 & 0111 = 0000 (count=3). Done. return 3 โœ“
05
Section Five ยท Implementation

Code โ€” Java & Python

Java โ€” Brian Kernighan
class Solution { public int hammingWeight(int n) { int count = 0; while (n != 0) { n &= (n - 1); // clear lowest set bit count++; } return count; } }
Python โ€” Brian Kernighan
class Solution: def hammingWeight(self, n: int) -> int: count = 0 while n: n &= n - 1 count += 1 return count
06
Section Six ยท Analysis

Complexity Analysis

ApproachTimeSpace
Shift & maskO(32)O(1)
Brian Kernighan โ† optimalO(k) k=set bitsO(1)
07
Section Seven ยท Edge Cases

Edge Cases & Pitfalls

CaseInputWhy It Matters
Zero0No set bits โ†’ 0.
All ones (32-bit)0xFFFFFFFF32 set bits.
Power of two16 = 10000โ‚‚Exactly 1 set bit โ†’ 1.
โš  Common Mistake: In Java, using >> (arithmetic right shift) instead of >>> (unsigned right shift). For negative numbers (high bit set), >> fills with 1s โ†’ infinite loop. Always use >>> for unsigned right shift, or use Brian Kernighan's trick (no shifting needed).

โ† Back to Math & Bit problems