Add Binary

Feb 07, 2018

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

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

 

We can use the Mod to get the rest of the number, and use division to get the carry.

For the first number, there’s no carry, so we add them first and do the %2 to get the first number, and then do a division to get the carry for the next number.

 

For example:

11 + 1

We add 1 + 1 first, and the mod is (1 + 1) % 2 = 0, and carry is (1 + 1) / 2 = 1.

Thus, the next number will be 1 + 0 + 1 (carry) = 2. Again, the mod is (1 + 0 + 1) % 2 = 0, and carry is (1 + 0 + 1) / 2 = 1.

The last number is 0 + 0 + 1 (carry) = 1,

Finally, contact all number into the result is: “1” + “0” + “0” = “100”;

 

Solution

var addBinary = function(a, b) {
    var al=a.length-1, bl=b.length-1;
    var result = "";
    var carry = 0;
    while(al>=0 || bl>=0) {
        var m = al >= 0 ? parseInt(a[al]) : 0;
        var n = bl >= 0 ? parseInt(b[bl]) : 0;
        carry += m + n;
        result = carry % 2 + result;
        carry = Math.floor(carry / 2);
        al --;
        bl --;
    }
    if(carry !== 0) {
        result = carry + result;
    }
    return result;
};