3370. Smallest Number With All Set Bits LeetCode Solution
In this guide, you will get 3370. Smallest Number With All Set Bits LeetCode Solution with the best time and space complexity. The solution to Smallest Number With All Set Bits problem is provided in various programming languages like C++, Java, and Python. This will be helpful for you if you are preparing for placements, hackathons, interviews, or practice purposes. The solutions provided here are very easy to follow and include detailed explanations.
Table of Contents
- Problem Statement
- Complexity Analysis
- Smallest Number With All Set Bits solution in C++
- Smallest Number With All Set Bits solution in Java
- Smallest Number With All Set Bits solution in Python
- Additional Resources

Problem Statement of 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
Complexity Analysis
- Time Complexity: O(\log n)
- Space Complexity: O(1)
3370. Smallest Number With All Set Bits LeetCode Solution in C++
class Solution {
public:
int smallestNumber(int n) {
return (1 << bitLength(n)) - 1;
}
private:
int bitLength(int n) {
return 32 - __builtin_clz(n);
}
};
/* code provided by PROGIEZ */
3370. Smallest Number With All Set Bits LeetCode Solution in Java
class Solution {
public int smallestNumber(int n) {
return (1 << bitLength(n)) - 1;
}
private int bitLength(int n) {
return 32 - Integer.numberOfLeadingZeros(n);
}
}
// code provided by PROGIEZ
3370. Smallest Number With All Set Bits LeetCode Solution in Python
class Solution:
def smallestNumber(self, n: int) -> int:
return (1 << n.bit_length()) - 1
# code by PROGIEZ
Additional Resources
- Explore all LeetCode problem solutions at Progiez here
- Explore all problems on LeetCode website here
Happy Coding! Keep following PROGIEZ for more updates and solutions.