Smallest Number With All Set Bits (LeetCode 3370): Solution and Explanation
Find the smallest number at or above n whose binary form is all 1s.
Intuition
A number made only of 1 bits is always one less than a power of two: 1, 3, 7, 15, 31, and so on. Those are the only candidates.
Each candidate comes from the previous one by shifting left and setting the new lowest bit, so the list is easy to walk.
The candidates grow in order, so the first one that reaches n is the smallest valid answer. It always has the same bit length as n.
Approach: Grow an all-ones value
- Set
x = 1. - While
x < n, setx = (x << 1) | 1. - Return
x.
Step-by-step example
n = 5
- 5 is 101 in binary.
- x = 1. 1 < 5, so grow to 11 (3).
- 3 < 5, so grow to 111 (7).
- 7 >= 5, so stop. Return 7.
Code: Python, Java, C++
1class Solution:
2 def smallestNumber(self, n: int) -> int:
3 x = 1
4 while x < n:
5 x = (x << 1) | 1
6 return x1class Solution {
2 public int smallestNumber(int n) {
3 int x = 1;
4 while (x < n) {
5 x = (x << 1) | 1;
6 }
7 return x;
8 }
9}1class Solution {
2public:
3 int smallestNumber(int n) {
4 int x = 1;
5 while (x < n) {
6 x = (x << 1) | 1;
7 }
8 return x;
9 }
10};Time and space complexity
O(log n)
x gains one bit per iteration and stops once it is as long as n.
O(1)
Only x is stored.
Other approaches
Bit length formula (time O(1), space O(1))
Compute L = n.bit_length() (or 32 - Integer.numberOfLeadingZeros(n)) and return (1 << L) - 1. No loop at all.
Smear the bits (time O(1), space O(1))
Copy the highest 1 bit into every lower position with x |= x >> 1, x |= x >> 2, x |= x >> 4 and so on. Any number turns into the all-ones number of the same length.
Common mistakes
- Using x <= n as the loop condition. When n is already all ones, such as 7, the answer is n itself and the loop must stop there.
- Returning the next power of two instead of one less than it. 8 is 1000, not all ones.
Frequently asked questions
Why is the answer always the same bit length as n?
The all-ones number with L bits, 2^L - 1, is the largest L-bit number. If n has L bits it is at most 2^L - 1, and the all-ones number with L - 1 bits is below every L-bit number.
How does this relate to Number Complement?
It builds the same mask. Number Complement XORs n with it to flip the bits; this problem returns the mask itself.
Can the answer overflow?
Not here, since n is at most 1000 and the answer is at most 1023. For n near 2^31 the answer 2^31 - 1 still fits in a signed 32-bit int.