# Adding binary without converting in JavaScript

JavascriptWeb DevelopmentFront End Technology

#### JavaScript for beginners

Best Seller

74 Lectures 10 hours

#### Modern Javascript for Beginners + Javascript Projects

Most Popular

112 Lectures 15 hours

#### The Complete Full-Stack JavaScript Course!

Best Seller

96 Lectures 24 hours

## 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';
};