LeetCode Entry

With All Set Bits

29.10.2025 easy 2025 kotlin rust

Next all bits set number

With All Set Bits easy blog post substack youtube

56938ebc-e4f5-4d0c-b54a-5848bbd610b3 (1).webp

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
    }