LeetCode Entry
With All Set Bits
Next all bits set number
With All Set Bits easy blog post substack youtube

Join me on Telegram
https://t.me/leetcode_daily_unstoppable/1157
Problem TLDR
Next all bits set number #easy #bits
Intuition
HighestOneBit shl 1 - 1
101
100 highest one bit
1000 shl 1
0111 -1
Approach
- how to find highestOneBit?
- we can brute force too
(n..2*n).first { (it+1) and it == 0 }
Complexity
-
Time complexity: \(O(1)\)
-
Space complexity: \(O(1)\)
Code
// 0ms
fun smallestNumber(n: Int) =
(n.takeHighestOneBit() shl 1) - 1
// 0ms
pub fn smallest_number(n: i32) -> i32 {
i32::MAX >> n.leading_zeros() - 1
}