LeetCode Entry

868. Binary Gap

22.02.2026 easy 2026 kotlin rust

Distance between onces in a binary

868. Binary Gap easy blog post substack youtube

8a9d5d07-3d31-4013-9259-420ff2a0c2f6 (1).webp

Join me on Telegram

https://t.me/leetcode_daily_unstoppable/1277

Problem TLDR

Distance between onces in a binary #easy

Intuition

The simplest way is to convert to string, then scan the positions.

Approach

  • n & (n-1) erases the last set bit
  • trailing_zeros, count_ones
  • regex to match (?=(10*1))
  • regex to split ^0+ 1 0+$

Complexity

  • Time complexity: \(O(log(n))\) or less

  • Space complexity: \(O(log(n))\) or less

Code

// 17ms
    fun binaryGap(n: Int) =
    (28 downTo 0).firstOrNull{("1"+"0".repeat(it)+"1") in n.toString(2)}?.plus(1)?:0
    /*
    Regex("(?=(10*1))").findAll(n.toString(2)).maxOfOrNull{it.groupValues[1].length-1}?:0
    */
// 0ms
    pub fn binary_gap(mut n: i32) -> i32 {
        (1..n.count_ones()).map(|_| {
            n >>= n.trailing_zeros() + 1; n.trailing_zeros() as i32 + 1 }).max().unwrap_or(0)
    }