JavaScript Program to Add n Binary Strings
Last Updated :
31 May, 2024
In this article, we are going to learn about Adding n binary strings by using JavaScript. Adding n binary strings in JavaScript refers to the process of performing binary addition on a collection of n binary strings, treating them as binary numbers, and producing the sum in binary representation as the result.
There are several methods that can be used to Add n binary strings by using javascript, which is listed below:
We will explore all the above methods along with their basic implementation with the help of examples.
Using for...in loop
In this approach, The custom function sums binary strings in inputStr using a for...in loop, converting them to decimal, and returning the result as a binary string
Syntax:
for (let i in obj1) {
// Prints all the keys in
// obj1 on the console
console.log(i);
};
Example: In this example,The addBinaryStrings function takes an array of binary strings, converts them to decimal, adds them together, and returns the sum as a binary string.
JavaScript
function addBinaryStrings(str1) {
let result = 0;
for (let i in str1) {
result += parseInt(str1[i], 2);
}
return result.toString(2);
}
let inputStr = ['0111', '1001'];
let sum = addBinaryStrings(inputStr);
console.log(sum);
Using reduce() method
In this approach, using Array.reduce(), define a function that takes an array of binary strings, converts them to decimal, accumulates their sum, and returns the result as a binary string. The accumulator starts at "0".
Syntax:
array.reduce( function(total, currentValue, currentIndex, arr),
initialValue );
Example: In this example,the addingBinaryStr function takes an array of binary strings, converts them to decimal, adds them with reduce, and returns the sum as a binary string.
JavaScript
function addingBinaryStr(str1) {
return str1.reduce((val1, val2) => {
let binary1 = parseInt(val1, 2);
let binary2 = parseInt(val2, 2);
let sum = binary1 + binary2;
return sum.toString(2);
}, "0");
}
let inputStr = ['0111', '1001'];
let result = addingBinaryStr(inputStr);
console.log(result);
Using parseInt() and toString() method
In this approach,we Add binary strings by converting them to integers using parseInt with base 2, then summing them, and finally converting the result back to binary using toString(2).
Syntax:
parseInt(Value, radix) //parseInt()
num.toString(base) //toString()
Example: In this example, we are using above-explained approach.
JavaScript
let binary1 = "0111";
let binary2 = "1001";
// Parse binary string 'binary2' to an integer
let num1 = parseInt(binary1, 2);
// Parse binary string 'binary2' to an integer
let num2 = parseInt(binary2, 2);
// Add the two integers
let sum = num1 + num2;
// Convert the sum back to a binary string
let result = sum.toString(2);
console.log(result);
Bitwise Addition
In this approach, we perform binary addition using bitwise operations. We traverse each bit of the binary strings from the least significant bit (rightmost) to the most significant bit (leftmost). We maintain carry during addition and update the result accordingly.
Example:
JavaScript
function addBinaryStrings(str1) {
let result = '';
let carry = 0;
// Iterate through each bit from right to left
for (let i = str1[0].length - 1; i >= 0; i--) {
let sum = carry;
// Add the corresponding bits of all binary strings
for (let j = 0; j < str1.length; j++) {
sum += parseInt(str1[j][i]) || 0;
}
// Calculate current bit of result
result = (sum % 2) + result;
// Calculate carry for the next bit addition
carry = Math.floor(sum / 2);
}
// Add carry if present
if (carry) {
result = carry + result;
}
return result;
}
let inputStr = ['0111', '1001'];
let sum = addBinaryStrings(inputStr);
console.log(sum);
Similar Reads
Non-linear Components In electrical circuits, Non-linear Components are electronic devices that need an external power source to operate actively. Non-Linear Components are those that are changed with respect to the voltage and current. Elements that do not follow ohm's law are called Non-linear Components. Non-linear Co
11 min read
JavaScript Tutorial JavaScript is a programming language used to create dynamic content for websites. It is a lightweight, cross-platform, and single-threaded programming language. It's an interpreted language that executes code line by line, providing more flexibility.JavaScript on Client Side: On the client side, Jav
11 min read
Web Development Web development is the process of creating, building, and maintaining websites and web applications. It involves everything from web design to programming and database management. Web development is generally divided into three core areas: Frontend Development, Backend Development, and Full Stack De
5 min read
Spring Boot Tutorial Spring Boot is a Java framework that makes it easier to create and run Java applications. It simplifies the configuration and setup process, allowing developers to focus more on writing code for their applications. This Spring Boot Tutorial is a comprehensive guide that covers both basic and advance
10 min read
React Interview Questions and Answers React is an efficient, flexible, and open-source JavaScript library that allows developers to create simple, fast, and scalable web applications. Jordan Walke, a software engineer who was working for Facebook, created React. Developers with a JavaScript background can easily develop web applications
15+ min read
React Tutorial React is a powerful JavaScript library for building fast, scalable front-end applications. Created by Facebook, it's known for its component-based structure, single-page applications (SPAs), and virtual DOM,enabling efficient UI updates and a seamless user experience.Note: The latest stable version
7 min read
JavaScript Interview Questions and Answers JavaScript is the most used programming language for developing websites, web servers, mobile applications, and many other platforms. In Both Front-end and Back-end Interviews, JavaScript was asked, and its difficulty depends upon the on your profile and company. Here, we compiled 70+ JS Interview q
15+ min read
Class Diagram | Unified Modeling Language (UML) A UML class diagram is a visual tool that represents the structure of a system by showing its classes, attributes, methods, and the relationships between them. It helps everyone involved in a projectâlike developers and designersâunderstand how the system is organized and how its components interact
12 min read
Backpropagation in Neural Network Back Propagation is also known as "Backward Propagation of Errors" is a method used to train neural network . Its goal is to reduce the difference between the modelâs predicted output and the actual output by adjusting the weights and biases in the network.It works iteratively to adjust weights and
9 min read
3-Phase Inverter An inverter is a fundamental electrical device designed primarily for the conversion of direct current into alternating current . This versatile device , also known as a variable frequency drive , plays a vital role in a wide range of applications , including variable frequency drives and high power
13 min read