use std::iter;
use std::mem;
impl Solution {
pub fn add_binary(mut a: String, mut b: String) -> String {
// let the length of a bigger than the length of b
if b.len() > a.len() {
mem::swap(&mut a, &mut b);
}
let mut ret = String::with_capacity(a.len());
let mut carry = 0;
for (ad, bd) in a
.chars()
.map(|c| c as u8 - b'0')
.rev()
.zip(b.chars().rev().map(|c| c as u8 - b'0').chain(iter::repeat(0)))
{
let mut x = ad + bd + carry;
if x >= 2 {
x -= 2;
carry = 1;
} else {
carry = 0;
}
ret.push((x + b'0') as char);
}
if carry == 1 {
ret.push('1');
}
unsafe {
ret.as_mut_vec().reverse(); // ret only contains '0' or '1' and their utf-8 width is 1, so it is safe to reverse the vec directly
}
ret
}
}
const addBinary = (a: string, b: string): string => {
if (b.length > a.length) {
const tmp = a;
a = b;
b = tmp;
}
let ret = "";
let carry = 0;
let ap = a.length - 1;
let bp = b.length - 1;
for (let i = 0;i < b.length;i++) {
const ad = a.charCodeAt(ap) - "0".charCodeAt(0);
ap -= 1;
const bd = b.charCodeAt(bp) - "0".charCodeAt(0);
bp -= 1;
let x = ad + bd + carry;
if (x >= 2) {
x -= 2;
carry = 1;
} else {
carry = 0;
}
ret += x;
}
for (let i = b.length;i < a.length;i++) {
const ad = a.charCodeAt(ap) - "0".charCodeAt(0);
ap -= 1;
let x = ad + carry;
if (x >= 2) {
x -= 2;
carry = 1;
} else {
carry = 0;
}
ret += x;
}
if (carry === 1) {
ret += 1;
}
return [...ret].reverse().join("");
};