Given two binary strings a and b, return their sum as a binary string.
Input: a = “11”, b = “1”
Output: “100”
// 将string 转为 number
let a = '1'
console.log(typeof +a) // number
// 若b为falsy,a为0,否则a = b
const a = b || 0
var addBinary = function(a, b) {
let carry = 0;
const arr1 = a.split('').reverse();
const arr2 = b.split('').reverse();
let res = '';
let i, j;
for(i = 0, j = 0; i < arr1.length || j < arr2.length; i++, j++) {
let sum = carry + (+arr1[i] || 0) + (+arr2[j] || 0);
if(sum > 1) {
carry = 1;
sum = sum % 2;
} else {
carry = 0;
}
res = `${sum}${res}`
}
if(carry) {
res = `${carry}${res}`
}
return res
};