Smallest Number With All Set Bits - Problem
Given a positive integer 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
Pattern Recognition: Numbers with All Set BitsThe 2^k - 1 Pattern12¹-11₂32²-111₂72³-1111₂152⁴-11111₂312⁵-111111₂632⁶-1111111₂Each number has exactly k consecutive 1s in binaryQuick check: (n & (n+1)) == 0 detects if n has all set bitsAlgorithm Steps1. Check if n already has all set bits: (n & (n+1)) == 02. If yes, return n3. If no, find highest bit position k in n4. Return (1 << k) - 1 // This gives us 2^k - 1🎯 Key Insight: Use mathematical pattern 2^k - 1 instead of checking each number individually
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

n
2n
Linearithmic
Space Complexity
O(1)

Only using constant extra space for calculations

n
2n
Linear Space

Constraints

  • 1 ≤ n ≤ 109
  • n is a positive integer
  • The result will fit in a 32-bit signed integer
Asked in
Google 45 Microsoft 38 Amazon 32 Meta 25
42.0K Views
Medium Frequency
~12 min Avg. Time
1.9K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen