Understanding and Implementing Binary Addition in JavaScript
Published in
3 min readOct 15, 2023
LeetCode 68 Add Binary
Binary addition is a fundamental operation in computer science, and it forms the basis for various computations in digital systems. In this article, we’ll delve into a JavaScript function for adding binary numbers.
The Code
function addBinary(a, b) {
let result = '';
let carry = 0;
let i = a.length - 1;
let j = b.length - 1;
while (i >= 0 || j >= 0) {
const bitA = i >= 0 ? parseInt(a[i]) : 0;
const bitB = j >= 0 ? parseInt(b[j]) : 0;
const sum = bitA + bitB + carry;
result = (sum % 2) + result;
carry = Math.floor(sum / 2);
i--;
j--;
}
if (carry > 0) {
result = carry + result;
}
return result;
}
Understanding the Code
Let’s break down the code step by step:
function addBinary(a, b)
: This declares a function namedaddBinary
that takes two binary stringsa
andb
as arguments.let result = '';
: This initializes an empty string calledresult
which will hold the final binary sum.let carry = 0;
: This variablecarry
is used to keep track of any carry that occurs during addition.let i = a.length - 1;
andlet j = b.length - 1;
: These variablesi
andj
are initialized to the last index of the input binary stringsa
andb
, respectively. These indices will be used to iterate through the binary digits from right to left.while (i >= 0 || j >= 0)
: This is a while loop that continues as long as there are digits to process in eithera
orb
.const bitA = i >= 0 ? parseInt(a[i]) : 0;
andconst bitB = j >= 0 ? parseInt(b[j]) : 0;
: These lines extract the binary digits at the current positionsi
andj
. Ifi
orj
is out of bounds, it assumes a value of 0.const sum = bitA + bitB + carry;
: This calculates the sum of the binary digits along with any carry from the previous addition.result = (sum % 2) + result;
: The least significant bit of the sum is added to the left of the result.carry = Math.floor(sum / 2);
: This calculates the carry, which will be added to the next iteration.i--;
andj--;
: These decrementsi
andj
to move to the next significant bit.if (carry > 0) { result = carry + result; }
: If there's a carry after the loop completes, it is added to the left of the result.return result;
: Finally, the binary sum is returned.
Conclusion
The addBinary
function allows for efficient addition of binary numbers in JavaScript. Understanding this code provides insight into fundamental concepts of binary arithmetic, which is crucial for anyone working in fields related to computer science or digital systems.
Happy coding! 🚀