SwiftSnippetRustProgrammingAlgorithm
Last updated at 2023-07-30

Algorithm Test: Binary Gap

ClickUp
Note
AI Status
Last Edit By
Last edited time
Jul 30, 2023 02:58 PM
Metatag
Slug
algorithm-test-binary-gap
Writer
Published
Published
Date
Jul 30, 2023
Category
Swift
Snippet
Rust
Programming
Algorithm
🚨
You may find this algorithm test somewhere else. Because my source prohibits me from reproducing the question, I will just give you a question hint, and you will be presented with the solution.

The Question

You are given arbitrary input in the form of a binary representation of a number.
Find the longest binary gap!

Example Input

  1. 101010
  1. 110011
  1. 111000
  1. 1001
  1. 111111
  1. 1000001
  1. 11010
  1. 1010010
  1. 1110101
  1. 11000011

Example Output

  1. 0
  1. 2
  1. 0
  1. 2
  1. 0
  1. 5
  1. 1
  1. 2
  1. 1
  1. 4

The Solution

Swift

public func binaryGap(_ binary : String) -> Int { var longest = 0 var current = 0 for i in binary { if i == "1" { longest = max(current, longest) current = 0 } else { current += 1 } } return longest }

Rust

pub fn binary_gap(binary: &str) -> i32 { let mut longest = 0; let mut current = 0; for i in binary.chars() { if i == '1' { longest = longest.max(current); current = 0; } else { current += 1; } } longest }

Discussion (0)

Related Posts