How to use parseInt() and toString() method In Javascript
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.
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);
Output
10000
JavaScript Program to Add n Binary Strings
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:
Table of Content
- Using for…in loop
- Using reduce() method
- Using parseInt() and toString() method
- Bitwise Addition
We will explore all the above methods along with their basic implementation with the help of examples.