#3370
Easy Algorithms Smallest number with all set bits
Math Bit Manipulation
80.3% acceptance
Feb 24, 2026
367
15
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.
Solution
Rust
Time O(1)
Space O(1)
impl Solution {
pub fn smallest_number(n: i32) -> i32 {
// Find number of bits in n; if n == 2^k - 1 return n, else return 2^k - 1
let bits = 32 - n.leading_zeros();
let candidate = (1 << bits) - 1;
candidate
}
}