Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Adding binary without converting in JavaScript
Adding binary numbers without converting to decimal requires simulating manual binary addition with carry handling. This approach processes bits from right to left, just like traditional addition.
Problem Statement
We need to write a JavaScript function that takes two binary strings and returns their sum as a binary string, without converting to decimal numbers.
Input:
const str1 = '1101'; const str2 = '10111';
Expected Output:
'100100'
Algorithm Overview
The solution works by:
- Reversing both strings to process from least significant bit
- Adding corresponding bits with carry propagation
- Building the result string from right to left
Implementation
const str1 = '1101';
const str2 = '10111';
const addBinary = (str1 = '', str2 = '') => {
str1 = str1.split('').reverse();
str2 = str2.split('').reverse();
let res = '', carry = 0;
while (str1.length || str2.length || carry) {
carry += (~~str1.shift()) + (~~str2.shift());
let bit = carry % 2;
res = bit + res;
carry = carry > 1;
}
return (+res) ? res.replace(/^0+/, '') : '0';
};
console.log(addBinary(str1, str2));
100100
Step-by-Step Breakdown
Let's trace through the addition of '1101' + '10111':
const addBinaryVerbose = (str1, str2) => {
console.log(`Adding: ${str1} + ${str2}`);
str1 = str1.split('').reverse();
str2 = str2.split('').reverse();
let res = '', carry = 0, step = 1;
while (str1.length || str2.length || carry) {
let bit1 = ~~str1.shift();
let bit2 = ~~str2.shift();
let sum = carry + bit1 + bit2;
console.log(`Step ${step}: ${bit1} + ${bit2} + ${carry}(carry) = ${sum}`);
let resultBit = sum % 2;
res = resultBit + res;
carry = sum > 1 ? 1 : 0;
console.log(`Result bit: ${resultBit}, New carry: ${carry}`);
step++;
}
return res;
};
console.log('Final result:', addBinaryVerbose('1101', '10111'));
Adding: 1101 + 10111 Step 1: 1 + 1 + 0(carry) = 2 Result bit: 0, New carry: 1 Step 2: 0 + 1 + 1(carry) = 2 Result bit: 0, New carry: 1 Step 3: 1 + 1 + 1(carry) = 3 Result bit: 1, New carry: 1 Step 4: 1 + 0 + 1(carry) = 2 Result bit: 0, New carry: 1 Step 5: 0 + 1 + 1(carry) = 2 Result bit: 0, New carry: 1 Step 6: 0 + 0 + 1(carry) = 1 Result bit: 1, New carry: 0 Final result: 100100
Key Points
-
~~converts undefined to 0 when one string is shorter -
carry > 1converts number to boolean (true = 1, false = 0) -
shift()removes and returns the first element - Leading zeros are removed with
replace(/^0+/, '')
Testing with Different Cases
const testCases = [
['1', '1'],
['1010', '1011'],
['1111', '1'],
['0', '0']
];
testCases.forEach(([a, b]) => {
console.log(`${a} + ${b} = ${addBinary(a, b)}`);
});
1 + 1 = 10 1010 + 1011 = 10101 1111 + 1 = 10000 0 + 0 = 0
Conclusion
Binary addition without decimal conversion mimics manual addition by processing bits right-to-left with proper carry handling. This approach efficiently handles binary strings of any length.
Advertisements
