Number of 1 Bits - Problem
Given a positive integer n, write a function that returns the number of set bits in its binary representation (also known as the Hamming weight).
A set bit is a bit that has a value of 1 in the binary representation of a number.
Input & Output
Example 1 — Basic Case
$
Input:
n = 11
›
Output:
3
💡 Note:
11 in binary is 1011, which has three 1-bits at positions 0, 1, and 3
Example 2 — Power of Two
$
Input:
n = 8
›
Output:
1
💡 Note:
8 in binary is 1000, which has exactly one 1-bit at position 3
Example 3 — All Bits Set
$
Input:
n = 7
›
Output:
3
💡 Note:
7 in binary is 111, which has three consecutive 1-bits
Constraints
- 1 ≤ n ≤ 231 - 1
Visualization
Tap to expand
Understanding the Visualization
1
Input
Given integer n = 11
2
Convert to Binary
11 → 1011 in binary
3
Count Set Bits
Count the number of 1s = 3
Key Takeaway
🎯 Key Insight: Use bit manipulation tricks like n & (n-1) to efficiently count only the set bits
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code