Problem Description
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.
Key Insights
- A number with all set bits in binary is of the form (2^m - 1) for some integer m.
- The smallest number with all set bits greater than or equal to n can be found by determining the next power of two that covers n.
- This can be efficiently calculated using bit manipulation.
Space and Time Complexity
Time Complexity: O(log n)
Space Complexity: O(1)
Solution
To solve the problem, we can use the following approach:
- Identify the smallest power of two greater than or equal to n.
- Generate the number with all set bits corresponding to that power of two.
- This is done by taking the power of two and subtracting one from it.
For example, for n = 5, the next power of two is 8 (2^3), and the smallest number with all set bits is 7 (which is 2^3 - 1).