Problem Description
Given a positive number n, find the smallest number x greater than or equal to n such that the binary representation of x contains only set bits (i.e., all 1's). Numbers with only set bits are of the form (2^k - 1). For example, if n = 5, then x = 7 because 7 in binary is "111".
Key Insights
- Numbers with only set bits are of the form (2^k - 1) for some integer k.
- To solve the problem, find the smallest k such that (2^k - 1) is greater than or equal to n.
- This problem takes advantage of bit manipulation and properties of numbers represented in binary.
Space and Time Complexity
Time Complexity: O(log n) – The loop iterates roughly the number of bits required to represent n. Space Complexity: O(1) – Only a few variables are used.
Solution
We iterate over increasing values of k and compute candidate = (2^k - 1). When candidate is greater than or equal to n, we return candidate. We use arithmetic operations without any additional data structure.