Skip to content
Discussion options

You must be logged in to vote

We need to find the smallest number ≥ n that has all 1s in its binary representation.

The key insight is that numbers with all set bits are of the form 2^k - 1 (like 1, 3, 7, 15, 31, etc.). So I need to find the smallest number of this form that is ≥ n.

Here's my approach:

  1. Find the number of bits needed to represent n
  2. The candidate numbers are (1 << k) - 1 where k is the bit length
  3. If n itself is already all 1s, return n
  4. Otherwise, return the next number with all 1s

Let's implement this solution in PHP: 3370. Smallest Number With All Set Bits

<?php
/**
 * @param Integer $n
 * @return Integer
 */
function smallestNumber($n) {
    // If n is already all 1s, return it
    if (($n & ($n + 1)…

Replies: 1 comment 2 replies

Comment options

You must be logged in to vote
2 replies
@basharul-siddike
Comment options

@mah-shamim
Comment options

mah-shamim Oct 29, 2025
Maintainer Author

Answer selected by basharul-siddike
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
question Further information is requested easy Difficulty
2 participants