2025-10-29 Daily Challenge

Today I have done leetcode's October LeetCoding Challenge with cpp.

October LeetCoding Challenge 29

Description

Smallest Number With All Set Bits

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

 

Example 1:

Input: n = 5

Output: 7

Explanation:

The binary representation of 7 is "111".

Example 2:

Input: n = 10

Output: 15

Explanation:

The binary representation of 15 is "1111".

Example 3:

Input: n = 3

Output: 3

Explanation:

The binary representation of 3 is "11".

 

Constraints:

  • 1 <= n <= 1000

Solution

class Solution {
public:
  int smallestNumber(int n) {
    int base = 1;
    while((1 << base) - 1 < n) {
      base += 1;
    }
    return (1 << base) - 1;
  }
};

// Accepted
// 608/608 cases passed (0 ms)
// Your runtime beats 100 % of cpp submissions
// Your memory usage beats 99.74 % of cpp submissions (8 MB)