hongkongbboy
hongkongbboy

Reputation: 310

JavaScript (Add Binary)

This is the prompt:

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

The input strings are both non-empty and contains only characters 1 or 0.

Example 1:

Input: a = "11", b = "1"
Output: "100"
Example 2:

Input: a = "1010", b = "1011"
Output: "10101"

This is my code:

var addBinary = function(a, b) {
    var c = (Number(a) + Number(b)).toString();
    var binaryTotal = "";
    var temp = 0;
    for (var i=c.length - 1; i>=0; i--) {
        console.log(temp, 'temp')
        console.log(c[i], 'c[i]')
        c[i] = (temp + Number(c[i])).toString();
        console.log(c[i], 'after')
        if (c[i] === '3') {
            binaryTotal = '1' + binaryTotal;
            temp = 1;
        } else if (c[i] === '2') {
            binaryTotal = '0' + binaryTotal;
            temp = 1;
        } else if (c[i] === '1') {
            binaryTotal = '1' + binaryTotal;
            temp = 0;
        } else if (c[i] === '0') {
            binaryTotal = '0' + binaryTotal;
            temp = 0;
        }
        if (temp === 1 && i === 0) {
            binaryTotal = '1' + binaryTotal;
        }
        console.log(binaryTotal, 'binaryTotal')
    }
    return binaryTotal;
};

If I test with input a = "11", b = "1", my output is showing "10", but I was expecting "100". I think there is something wrong with this part of my code c[i] = (temp + Number(c[i])).toString(); and I don't get what's wrong. I was expecting c[1] to equal to 2 when i equals 0, but I am not getting that. I tried to switch Number with parseInt and same result. Can someone explain?

This is the result from stdout:

0 temp
2 c[i]
2 after
0 binaryTotal
1 temp
1 c[i]
1 after
10 binaryTotal

Upvotes: 1

Views: 3029

Answers (2)

Nina Scholz
Nina Scholz

Reputation: 386654

You could iterate the strings from the end and build a new array by respecting the carry.

function add(a, b) {
    let values = [],
        i = a.length - 1,
        j = b.length - 1,
        carry = 0;

    while (i >= 0 || j >= 0 || carry) {
        carry += (+a[i] || 0) + (+b[j] || 0);
        values.unshift(carry % 2);
        carry >>= 1; // or Math.floor(carry / 2)
        i--;
        j--;
    }
    return values.join('');
}

console.log(add('1', '111111'));
console.log(add('111111', '1'));

Upvotes: 1

Touffy
Touffy

Reputation: 6561

This is the lazy answer:

function addBinary(a, b) {
  return (parseInt(a, 2) + parseInt(b, 2)).toString(2)
}

This is the lazy answer with unlimited precision:

function addBigBinary(a, b) {
  return (BigInt('0b'+a) + BigInt('0b'+b)).toString(2)
}

Upvotes: 6

Related Questions