I’m solving leetcode problem of adding binary strings:
Given two binary strings a and b, return their sum as a binary string.
Example 1:
Input: a = "11", b = "1"
Output: "100"
Example 2:
Input: a = "1010", b = "1011"
Output: "10101"
To avoid using the error-prone manual indexing into both of the string I’m inclined to using iterators as follows:
pub fn add_binary(a: String, b: String) -> String {
let mut carry = 0;
let reversed_no_carry = a.chars().rev().chain(repeat('0'))
.zip(b.chars().rev().chain(repeat('0')))
.scan(&mut carry, |carry_ref, pair| {
let result = pair.0.to_digit(10).unwrap() + pair.1.to_digit(10).unwrap() + **carry_ref;
**carry_ref = result / 2;
Some((result % 2).to_string())
})
.take(max(a.len(), b.len()))
.collect::<String>();
once(carry)
.map_while(|v| if v == 1 { Some('1') } else { None })
.chain(reversed_no_carry.chars().rev())
.collect()
}
The problem is the code looks kind of cumbersome, especially the part of appending the carry bit if it’s non-zero. Is there a way to cut it down into using a single iterator pipeline or simplify it in any other way?