Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Algorithm to add binary arrays in JavaScript
In this problem statement, our target is to add two binary arrays with the help of JavaScript. So we will break down the problem step by step to ensure understanding.
What is a Binary Array?
A binary array is an array that represents a binary number. In a binary number system we have only two possible digits, 0 and 1. The binary array will have elements which can only be 0s and 1s. Every item in the array represents a bit of the binary number.
For example, we have a binary array [1, 0, 1, 0]. This array shows the binary number 1010. The leftmost bit 1 is the MSB (Most Significant Bit) and the rightmost bit 0 is the LSB (Least Significant Bit). Binary arrays are mostly used to represent and perform operations on binary numbers in programming languages.
Understanding the Problem
The problem is to add two binary arrays. A binary array consists of only 0s and 1s, representing binary numbers. For example, [1, 0, 1] represents binary number 101. We need to create an algorithm to perform binary addition on two binary arrays.
Logic for the Given Problem
Our algorithm will take two binary arrays as input. To add these binary arrays, we start from the rightmost bit and move towards the leftmost bit. We add the corresponding bits from both arrays along with any carry from the previous addition. The result will be an output array representing the sum of the two binary arrays.
Algorithm
Step 1: Initialize an empty array for storing the result of the binary array addition.
Step 2: Check if the two input arrays have the same length. If not, pad the shorter array with leading zeros to make their lengths equal. This step is essential because binary addition should be performed with the same number of digits.
Step 3: Initialize a carry variable to zero. The carry represents the value to be carried over to the next bit when the addition of two bits is 2 or greater.
Step 4: Traverse through the binary arrays from right to left (least to most significant bit).
Step 5: In each iteration, calculate the sum of current bits from both arrays plus the carry. Calculate the current result bit by taking modulo 2 of this sum.
Step 6: Calculate the new carry by taking the floor division of the sum divided by 2. Insert the calculated bit at the beginning of the result array.
Step 7: After processing all bits, check if there's a remaining carry. If yes, insert it at the beginning of the result array.
Step 8: Return the final result array as the sum of the binary arrays.
Example
// Function to add binary arrays
function addBinaryArrays(array1, array2) {
const result = [];
const length = Math.max(array1.length, array2.length);
let carry = 0;
// Pad shorter array with leading zeros
while (array1.length = 0; i--) {
const bitSum = array1[i] + array2[i] + carry;
const bit = bitSum % 2;
carry = Math.floor(bitSum / 2);
result.unshift(bit);
}
// Add the remaining carry, if any
if (carry > 0) {
result.unshift(carry);
}
return result;
}
// Define binary arrays
const array1 = [1, 0, 1, 1]; // Binary 1011 (decimal 11)
const array2 = [1, 1, 1, 0]; // Binary 1110 (decimal 14)
console.log("Array 1:", array1);
console.log("Array 2:", array2);
const sum = addBinaryArrays(array1, array2);
console.log("Sum:", sum);
// Verification: 1011 + 1110 = 11001 (decimal 11 + 14 = 25)
Array 1: [ 1, 0, 1, 1 ] Array 2: [ 1, 1, 1, 0 ] Sum: [ 1, 1, 0, 0, 1 ]
Step-by-Step Addition Process
Let's trace through the addition of [1, 0, 1, 1] and [1, 1, 1, 0]:
function demonstrateAddition() {
const array1 = [1, 0, 1, 1];
const array2 = [1, 1, 1, 0];
console.log("Binary Addition Step by Step:");
console.log(" 1011");
console.log("+ 1110");
console.log("------");
let carry = 0;
const steps = [];
for (let i = 3; i >= 0; i--) {
const sum = array1[i] + array2[i] + carry;
const bit = sum % 2;
carry = Math.floor(sum / 2);
steps.push(`Position ${i}: ${array1[i]} + ${array2[i]} + ${carry === 0 ? 0 : 1} = ${sum} ? bit=${bit}, carry=${carry}`);
}
steps.forEach(step => console.log(step));
console.log("Final result: 11001");
}
demonstrateAddition();
Binary Addition Step by Step: 1011 + 1110 ------ Position 3: 1 + 0 + 0 = 1 ? bit=1, carry=0 Position 2: 1 + 1 + 0 = 2 ? bit=0, carry=1 Position 1: 0 + 1 + 1 = 2 ? bit=0, carry=1 Position 0: 1 + 1 + 1 = 3 ? bit=1, carry=1 Final result: 11001
Time and Space Complexity
The time complexity for this algorithm is O(n), where n is the length of the longest input array. The main loop iterates through each bit position once, performing constant-time operations. The space complexity is also O(n) because the result array stores the sum, which can be at most n+1 bits long.
Conclusion
This algorithm efficiently adds two binary arrays by simulating the process of binary addition with carry propagation. The function handles arrays of different lengths by padding with leading zeros and returns the correct binary sum as an array.
