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
JavaScript Program to Add Two Binary Strings
Here are the various ways to add two binary stringsUsing parseInt() and toString() The parseInt() method used here first converts the strings into the decimal. Ten of these converted decimal values are added together and by using the toString() method, we convert the sum back to the desired binary r
4 min read
JavaScript Program to Generate all Binary Strings From Given Pattern
In this article, we are going to learn about Generating all binary strings from a given pattern in JavaScript. Generating all binary strings from a given pattern involves creating a set of binary sequences that follow the pattern's structure, where specific positions in the sequences can be filled w
3 min read
JavaScript Program to Count Strings with Consecutive 1âs
Given a number n, count the Optimized number of n-length strings with consecutive 1s in them.Examples:Input : n = 2Output : 1There are 4 strings of length 2, thestrings are 00, 01, 10 and 11. Only the string 11 has consecutive 1's.Input : n = 3Output : 3There are 8 strings of length 3, thestrings ar
7 min read
JavaScript Program to Convert Decimal to Binary
In this article, we are going to learn the conversion of numeric values from decimal to binary. Binary is a number system with 2 digits (0 and 1) representing all numeric values. Given a number N which is in decimal representation. our task is to convert the decimal representation of the number to i
5 min read
JavaScript Program to FindNumber of Flips to make Binary String Alternate
In this problem, we aim to determine the minimum number of flips needed to transform a binary string into an alternating sequence of '0's and '1's. A flip refers to changing a '0' to '1' or a '1' to '0'. The objective is to find the most efficient way to achieve this alternating pattern.Examples:Inp
4 min read
JavaScript Program to Check if all Bits can be made Same by Single Flip
In this article, we will explore how to determine if it's possible to make all bits the same in a binary string by performing a single flip operation. We will cover various approaches to implement this in JavaScript and provide code examples for each approach.Examples:Input: 1101Output: YesExplanati
5 min read
C Program to Add 2 Binary Strings
Given two Binary Strings, we have to return their sum in binary form.Approach: We will start from the last of both strings and add it according to binary addition, if we get any carry we will add it to the next digit.Input: 11 + 11Output: 110C// C Program to Add 2 Binary Strings // and Print their B
8 min read
Java Program to Add Characters to a String
We will be discussing out how to add character to a string at particular position in a string in java. It can be interpreted as follows as depicted in the illustration what we are trying to do which is as follows: Illustration: Input: Input custom string = HelloOutput: --> String to be added 'Gee
4 min read
PHP Program to Add Two Binary Numbers
Given Two binary numbers, the task is to add two binary numbers in PHP. Examples: Input: num1 = '1001', num2 = '1010'Output: 10011Input: num1 = '1011', num2 = '1101'Output: 11000There are two methods to add to binary numbers, these are: Table of Content Using bindec() and decbin() FunctionsUsing bas
1 min read
Java Program to Count Number of Digits in a String
The string is a sequence of characters. In java, objects of String are immutable. Immutable means that once an object is created, it's content can't change. Complete traversal in the string is required to find the total number of digits in a string. Examples: Input : string = "GeeksforGeeks password
2 min read