Data Structures & Algorithms Bit Manipulation
💡
Exercise 154

Number of 1 Bits 15 XP Easy

LeetCode Ctrl+Enter Run Ctrl+S Save

Count the number of '1' bits in an integer (Hamming weight).

# Method 1: n & 1 to check last bit, then n >>= 1 # Method 2: n & (n-1) removes lowest set bit — count iterations # n=11 → 1011 → three 1-bits

The n &= (n-1) trick is elegant: it removes one set bit per iteration, so we loop exactly count times.

💡 Pro tip: Understand this problem deeply — don't just memorize the code. Try explaining the approach out loud as if teaching a friend. If you can explain it simply, you truly understand it!

📋 Instructions
Count 1-bits for n=11 and n=128.
While n > 0: n &= (n-1), count += 1. The loop runs exactly 'number of 1-bits' times.
🧪 Test Cases
Input
hammingWeight(11)
Expected
3
Test case 1
Input
hammingWeight(128)
Expected
1
Test case 2
main.py
Hi! I'm Rex 👋
Output
Ready. Press ▶ Run or Ctrl+Enter.