67. Add Binary

Solution

/**
 * @param {string} a
 * @param {string} b
 * @return {string}
 */
 var addBinary = function(a, b) {
    a = a.split('').reverse();
    b = b.split('').reverse();
    const res = [];

    let carry = 0;
    for (let i = 0; i < Math.max(a.length, b.length); i++) {
        const total = Number(a[i] || '0') + Number(b[i] || '0') + carry;
        res.unshift(total % 2);
        carry = total / 2 | 0;

    }
    if (carry) {
        res.unshift(1);
    }
    return res.join('');
};

Complexity

  • Time Complexity: O(N), where N is the size of the largest between a and b.
  • Space Complexity: O(N), where N is the size of res.

All Solutions