Smallest Number With All Set Bits - Problem
You are given a positive number n. Return the smallest number x greater than or equal to n, such that the binary representation of x contains only set bits (all bits are 1).
A number with all set bits means every bit position in its binary representation is 1. For example:
- 1 (binary: 1) - all bits are 1
- 3 (binary: 11) - all bits are 1
- 7 (binary: 111) - all bits are 1
- 15 (binary: 1111) - all bits are 1
Input & Output
Example 1 — Basic Case
$
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 — Already All Set Bits
$
Input:
n = 3
›
Output:
3
💡 Note:
3 in binary is 11. Since all bits are already set, return 3.
Example 3 — Single Bit
$
Input:
n = 1
›
Output:
1
💡 Note:
1 in binary is 1. Since the only bit is set, return 1.
Constraints
- 1 ≤ n ≤ 109
Visualization
Tap to expand
Understanding the Visualization
1
Input
Given positive integer n
2
Process
Find smallest x ≥ n where all bits are 1
3
Output
Return the number with all set bits
Key Takeaway
🎯 Key Insight: All numbers with set bits follow 2^k - 1 pattern, so calculate directly instead of checking each number
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code