Adding binary strings together JavaScript

JavascriptWeb DevelopmentFront End TechnologyObject Oriented Programming

We are required to write a JavaScript function that takes in two binary strings. The function should return the sum of those two-binary string as another binary string.

For example −

If the two strings are −

const str1 = "1010";
const str2 = "1011";

Then the output should be −

const output = '10101';

Example

const str1 = "1010";
const str2 = "1011";
const addBinary = (str1, str2) => {
   let carry = 0;
   const res = [];
   let l1 = str1.length, l2 = str2.length;
   for (let i = l1 - 1, j = l2 - 1; 0 <= i || 0 <= j; --i, --j) {
      let a = 0 <= i ? Number(str1[i]) : 0,
      b = 0 <= j ? Number(str2[j]) : 0;
      res.push((a + b + carry) % 2);
      carry = 1 < a + b + carry;
   };
   if (carry){
      res.push(1);
   }
   return res.reverse().join('');
};
console.log(addBinary(str1, str2));

Output

And the output in the console will be −

10101
raja
Published on 23-Nov-2020 11:43:09
Advertisements