Understanding and Implementing Binary Addition in JavaScript

Akhil Kumar
TheCodingWay
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:

  1. function addBinary(a, b): This declares a function named addBinary that takes two binary strings a and b as arguments.
  2. let result = '';: This initializes an empty string called result which will hold the final binary sum.
  3. let carry = 0;: This variable carry is used to keep track of any carry that occurs during addition.
  4. let i = a.length - 1; and let j = b.length - 1;: These variables i and j are initialized to the last index of the input binary strings a and b, respectively. These indices will be used to iterate through the binary digits from right to left.
  5. while (i >= 0 || j >= 0): This is a while loop that continues as long as there are digits to process in either a or b.
  6. const bitA = i >= 0 ? parseInt(a[i]) : 0; and const bitB = j >= 0 ? parseInt(b[j]) : 0;: These lines extract the binary digits at the current positions i and j. If i or j is out of bounds, it assumes a value of 0.
  7. const sum = bitA + bitB + carry;: This calculates the sum of the binary digits along with any carry from the previous addition.
  8. result = (sum % 2) + result;: The least significant bit of the sum is added to the left of the result.
  9. carry = Math.floor(sum / 2);: This calculates the carry, which will be added to the next iteration.
  10. i--; and j--;: These decrements i and j to move to the next significant bit.
  11. if (carry > 0) { result = carry + result; }: If there's a carry after the loop completes, it is added to the left of the result.
  12. 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! 🚀

AI generated Hash “Understanding and Implementing Binary Addition in JavaScript”

--

--