67. Add Binary


Problem

https://leetcode.com/problems/add-binary/

Given two binary strings, return their sum (also a binary string).

For example,
a = "11"
b = "1"
Return "100".

Solution

It would be nice to do this:

/**
 * @param {string} a
 * @param {string} b
 * @return {string}
 */
var addBinary = function(a, b) {
    return (Number.parseInt(a, 2) + Number.parseInt(b, 2)).toString(2)
};

But unfortunately the binary string could be too big.

So just write a binary add:

/**
 * @param {string} a
 * @param {string} b
 * @return {string}
 */
var addBinary = function(a, b) {
    if (isNaN(parseInt(a,2)) || isNaN(parseInt(b,2))) {
        return ''
    }

    let result = ''
    let carry = 0
    for (let i = a.length-1, j = b.length-1; i >= 0 || j >= 0; i -= 1, j -= 1) {
        let ai = i < 0? 0: a[i]*1
        let bj = j < 0? 0: b[j]*1
        let sum = ai + bj + carry
        if (sum === 1 || sum === 3) {
            result = '1' + result
        } else {
            result = '0' + result
        }
        if (sum > 1) {
            carry = 1
        } else {
            carry = 0
        }
    }

    if (carry > 0) {
        result = '1' + result
    }

    return result
};

results matching ""

    No results matching ""