Adding binary without converting in JavaScript


Problem

We are required to write a JavaScript function that takes in two binary strings str1 and str2 as the first and the second argument

Our function should return the sum of the two binary numbers. We are not allowed to convert the binary numbers into decimal and then add and the resulting sum should contain no zeros at all.

For example, if the input to the function is −

Input

const str1 = '1101';
const str2 = '10111';

Output

const output = '100100';

Example

Following is the code −

 Live Demo

const str1 = '1101';
const str2 = '10111';
const addBinary = (str1 = '', str2 = '') => {
   str1 = str1.split('').reverse();
   str2 = str2.split('').reverse();
   let res = '', temp = 0;

   while (str1.length || str2.length || temp) {
      temp += (~~str1.shift()) + (~~str2.shift());
      let mod = temp % 2;
      res = mod + res;
      temp = temp > 1;
   };
   return (+res) ? res.replace(/^0+/, '') : '0';
};
console.log(addBinary(str1, str2));

Output

100100

Updated on: 22-Apr-2021

167 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements