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
Smallest Number With All Set Bits: n = 5Input: 5Binary: 101Not all bits 1ProcessFind next 2^k - 1where k > log₂(5)Output: 7Binary: 111All bits are 1 ✓Numbers with all set bits: 1, 3, 7, 15, 31, 63, ...Pattern: 2¹-1, 2²-1, 2³-1, 2⁴-1, 2⁵-1, 2⁶-1, ...For n=5, answer is 7 = 2³-1
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
Asked in
Google 25 Microsoft 18 Amazon 15
12.5K Views
Medium Frequency
~15 min Avg. Time
485 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