Given two binary strings, return their sum (also a binary string).
The input strings are both non-empty and contains only characters 1
or 0
.
Example 1:
Input: a = "11", b = "1"
Output: "100"
Example 2:
Input: a = "1010", b = "1011"
Output: "10101"
Runtime: 64 ms, faster than 48.07% of JavaScript online submissions for Add Binary.
/**
* @param {string} a
* @param {string} b
* @return {string}
*/
var addBinary = function(a, b) {
const lenA = a.length;
const lenB = b.length;
let i = lenA - 1;
let j = lenB - 1;
let carry = 0;
const result = [];
while(i >= 0 || j >= 0) {
if (a[i] === '1' && b[j] === '1') {
result.push(carry);
carry = 1;
} else if (a[i] === '0' && b[j] === '0') {
result.push(carry);
carry = 0;
} else if ((a[i] === '1' && b[j] !== '1') || (a[i] !== '1' && b[j] === '1')) {
if (carry) {
result.push(0);
} else {
result.push(1);
}
} else {
result.push(carry);
carry = 0;
}
i--;
j--;
}
if (carry) {
result.push(carry);
}
return result.reverse().join('');
};
Runtime: 60 ms, faster than 98.45% of JavaScript online submissions for Add Binary.
/**
* @param {string} a
* @param {string} b
* @return {string}
*/
var addBinary = function(a, b) {
const lenA = a.length;
const lenB = b.length;
let i = lenA - 1;
let j = lenB - 1;
let carry = 0;
let result = '';
while(i >= 0 || j >= 0) {
if (a[i] === '1' && b[j] === '1') {
result = carry + result;
carry = 1;
} else if (a[i] === '0' && b[j] === '0') {
result = carry + result;
carry = 0;
} else if ((a[i] === '1' && b[j] !== '1') || (a[i] !== '1' && b[j] === '1')) {
if (carry) {
result = '0' + result;
} else {
result = '1' + result;
}
} else {
result = carry + result;
carry = 0;
}
i--;
j--;
}
if (carry) {
result = carry + result;
}
return result;
};