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
- 101010
- 110011
- 111000
- 1001
- 111111
- 1000001
- 11010
- 1010010
- 1110101
- 11000011
Example Output
- 0
- 2
- 0
- 2
- 0
- 5
- 1
- 2
- 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 }