Basics of Binary Addition −
The four rules of binary addition are −
0 + 0 = 0 0 + 1 = 1 1 + 0 = 1 1 + 1 = 10
Keeping these points in mind, binary addition is very similar to the decimal addition (that follows the carry principle).
We are required to write a JavaScript function that takes in two arrays that contains only binary strings. (either '0' or '1').
The function should add the corresponding binary bits from the arrays and return a new array that contains the additional result of those arrays.
For example − If the input arrays are −
const arr1 = ['1', '0', '1']; const arr2 = ['1', '0', '1'];
Then the output should be −
const output = ['1', '0', '1', '0'];
Example
The code for this will be −
const arr1 = ['1', '0', '1']; const arr2 = ['1', '0', '1']; const addBinary = (arr1 = [], arr2 = []) => { const str1 = arr1.join(''); const str2 = arr2.join(''); let carry = 0, temp = 0, res = ''; for(let i = Math.max(str1.length, str2.length) − 1; i >= 0; i−−){ const el1 = +str1[i] || 0; const el2 = +str2[i] || 0; if(el1 + el2 + carry > 1){ temp = 0; carry = 1; }else{ temp = el1 + el2 + carry; carry = 0; }; res = temp + res; }; if(carry){ res = carry + res; }; return res.split(''); }; console.log(addBinary(arr1, arr2));
Output
And the output in the console will be −
[ '1', '0', '1', '0' ]