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 INPUT n = 5 Binary of 5: 1 0 1 0 Has a zero bit! Goal: Find x >= n where all bits are 1 5 ? ALGORITHM STEPS 1 Find bit count Count bits in n: 3 bits 2 Create all 1s mask x = (1 << 3) - 1 = 7 1 << 3 = 1000 (8) 8 - 1 = 0111 (7) 3 Check if x >= n 7 >= 5? Yes! 4 Return result If not, add more bits Formula: x = (1 << bits) - 1 FINAL RESULT Output: 7 Binary of 7: 1 1 1 All bits are 1! OK Verification: - 7 >= 5 OK - 7 = 111 (all 1s) OK - Smallest valid: 7 OK Key Insight: Numbers with all set bits follow pattern: 1, 3, 7, 15, 31... which equals (2^k - 1). Find smallest k where (2^k - 1) >= n. This is O(log n) time, O(1) space complexity. TutorialsPoint - Smallest Number With All Set Bits | Single Pass Optimal
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