Smallest Number With All Set Bits - Problem
Given a positive integer
In other words, find the smallest number greater than or equal to
Examples:
• If
• If
• If
n, you need to find the smallest number x where x >= n and the binary representation of x contains only set bits (only 1s).In other words, find the smallest number greater than or equal to
n that looks like 111...111 in binary (a sequence of consecutive 1s).Examples:
• If
n = 5 (binary: 101), return 7 (binary: 111)• If
n = 10 (binary: 1010), return 15 (binary: 1111)• If
n = 7 (binary: 111), return 7 (already all set bits) Input & Output
example_1.py — Small number
$
Input:
n = 5
›
Output:
7
💡 Note:
5 in binary is 101. The smallest number ≥ 5 with all set bits is 7 (111 in binary).
example_2.py — Already all set bits
$
Input:
n = 7
›
Output:
7
💡 Note:
7 in binary is 111, which already has all set bits, so we return 7 itself.
example_3.py — Larger number
$
Input:
n = 10
›
Output:
15
💡 Note:
10 in binary is 1010. The smallest number ≥ 10 with all set bits is 15 (1111 in binary).
Visualization
Tap to expand
Understanding the Visualization
1
Identify Pattern
Numbers with all set bits: 1, 3, 7, 15, 31... follow 2^k - 1
2
Find Position
Determine the highest bit position in the input number n
3
Calculate Result
Use bit shifting to compute 2^k - 1 efficiently
4
Optimize Check
Use (n & (n+1)) == 0 to detect if n already has all set bits
Key Takeaway
🎯 Key Insight: Numbers with all set bits follow the pattern 2^k - 1. Find the minimum k where 2^k - 1 ≥ n for O(log n) solution.
Time & Space Complexity
Time Complexity
O(log n)
We only need to find the position of the highest bit, which takes logarithmic time
⚡ Linearithmic
Space Complexity
O(1)
Only using constant extra space for calculations
✓ Linear Space
Constraints
- 1 ≤ n ≤ 109
- n is a positive integer
- The result will fit in a 32-bit signed integer
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code