
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Add Binary Without Converting in JavaScript
Problem
We are required to write a JavaScript function that takes in two binary strings str1 and str2 as the first and the second argument
Our function should return the sum of the two binary numbers. We are not allowed to convert the binary numbers into decimal and then add and the resulting sum should contain no zeros at all.
For example, if the input to the function is −
Input
const str1 = '1101'; const str2 = '10111';
Output
const output = '100100';
Example
Following is the code −
const str1 = '1101'; const str2 = '10111'; const addBinary = (str1 = '', str2 = '') => { str1 = str1.split('').reverse(); str2 = str2.split('').reverse(); let res = '', temp = 0; while (str1.length || str2.length || temp) { temp += (~~str1.shift()) + (~~str2.shift()); let mod = temp % 2; res = mod + res; temp = temp > 1; }; return (+res) ? res.replace(/^0+/, '') : '0'; }; console.log(addBinary(str1, str2));
Output
100100
Advertisements