Overview
Given two binary strings a and b, return their sum as a binary string.
Constraints
1 <= a.length, b.length <= 10,000- Each string consists only of '0' or '1'.
- Neither string has leading zeros (except "0" itself).
Examples
addBinary("11", "1"); // => "100"
addBinary("1010", "1011"); // => "10101"Solution
Reveal solution
function addBinary(a, b) {
let i = a.length - 1, j = b.length - 1, carry = 0;
let result = "";
while (i >= 0 || j >= 0 || carry) {
let sum = carry;
if (i >= 0) sum += +a[i--];
if (j >= 0) sum += +b[j--];
result = (sum % 2) + result;
carry = Math.floor(sum / 2);
}
return result;
}Resources
add-binary.js
Add Binary
easycodingAlgorithmsStrings
Overview
Given two binary strings a and b, return their sum as a binary string.
Constraints
1 <= a.length, b.length <= 10,000- Each string consists only of '0' or '1'.
- Neither string has leading zeros (except "0" itself).
Examples
addBinary("11", "1"); // => "100"
addBinary("1010", "1011"); // => "10101"Solution
Reveal solution
function addBinary(a, b) {
let i = a.length - 1, j = b.length - 1, carry = 0;
let result = "";
while (i >= 0 || j >= 0 || carry) {
let sum = carry;
if (i >= 0) sum += +a[i--];
if (j >= 0) sum += +b[j--];
result = (sum % 2) + result;
carry = Math.floor(sum / 2);
}
return result;
}Resources
NameTopicDifficulty
103 of 103 problems