Smallest Number With All Set Bits - LeetCode #3360
1 min
The Smallest Number of All Ones — LeetCode #3360
Problem: Given a positive number , find the smallest number whose binary representation consists only of 1 bits (for example: 1, 3, 7, 15, …).
📝 Summary
This exercise is useful for practicing bit manipulation techniques and recognizing patterns in binary representation of numbers.
📋 Problem Statement
- Input: A positive number .
- Output: The smallest number such that the binary representation of contains only ones.
Constraints:
📊 Examples
| bin() | result | bin(result) | |
|---|---|---|---|
| 5 | 0101 | 7 | 111 |
| 10 | 1010 | 15 | 1111 |
| 3 | 11 | 3 | 11 |
💡 Key Observations
Numbers with all bits set to 1 have the form (for example: 1, 3, 7, 15, 31, …). The problem reduces to finding the smallest such that .
🧠 Strategy
- Calculate :
- Obtain the result:
🛠️ Implementation (TypeScript / JavaScript)
export function smallestNumber(n: number): number {
// Find the exponent k such that 2^k - 1 >= n
const k = Math.ceil(Math.log2(n + 1))
// Calculate 2^k - 1
return (1 << k) - 1
}▶️ Execution Example
console.log(smallestNumber(5)) // 7
console.log(smallestNumber(10)) // 15
console.log(smallestNumber(3)) // 3
console.log(smallestNumber(1000)) // 1023⏱️ Complexity Analysis
- Time:
- Space:
⚠️ Edge Cases and Additional Tests
- → output: 1
- → output: 1023 ()
🛎️ Implementation Details
Math.log2is used to calculate the base-2 logarithm of .Math.ceilrounds up to the nearest integer.- The left bit shift operator (
<<) calculates . - 1 is subtracted to obtain the number with all bits set.
✅ Conclusion
This approach leverages the structural property of numbers composed only of ones in binary and allows calculating the solution in constant time.