Smallest Number With All Set Bits

easy bit manipulation math powers of two

Problem

You are given a positive integer n. Return the smallest number x that is greater than or equal to n whose binary representation contains only set bits (all 1s), i.e. a number of the form 2k − 1 such as 1, 3, 7, 15, 31, …

Inputn = 5
Output7
The binary representation of 7 is "111" — the smallest all-ones number that is ≥ 5.

def smallestNumber(n):
    # Smallest all-ones number is 1 (binary "1").
    x = 1
    # Append a 1 bit each step (x*2 + 1) until x reaches n.
    while x < n:
        x = x * 2 + 1
    # x is now the smallest 2^k - 1 that is >= n.
    return x
function smallestNumber(n) {
  // Smallest all-ones number is 1 (binary "1").
  let x = 1;
  // Append a 1 bit each step (x*2 + 1) until x reaches n.
  while (x < n) {
    x = x * 2 + 1;
  }
  // x is now the smallest 2^k - 1 that is >= n.
  return x;
}
int smallestNumber(int n) {
    // Smallest all-ones number is 1 (binary "1").
    int x = 1;
    // Append a 1 bit each step (x*2 + 1) until x reaches n.
    while (x < n) {
        x = x * 2 + 1;
    }
    // x is now the smallest 2^k - 1 that is >= n.
    return x;
}
int smallestNumber(int n) {
    // Smallest all-ones number is 1 (binary "1").
    int x = 1;
    // Append a 1 bit each step (x*2 + 1) until x reaches n.
    while (x < n) {
        x = x * 2 + 1;
    }
    // x is now the smallest 2^k - 1 that is >= n.
    return x;
}
Time: O(log n) Space: O(1)