Description
Given two binary strings a and b, return their sum as a binary string.
Example 1:
Input: a = "11", b = "1" Output: "100"
Example 2:
Input: a = "1010", b = "1011" Output: "10101"
Constraints:
1 <= a.length, b.length <= 104aandbconsist only of'0'or'1'characters.- Each string does not contain leading zeros except for the zero itself.
Solutions
This solution uses a counter-based loop to access digits from right to left, converts digits to numbers for arithmetic, uses bitwise AND (sum & 1) to check if the sum is odd for the result bit, and determines carry by checking if sum is at least 2.
Language: javascript(2026-02-15 10:34)DONE
CPU Performance70.14%
Memory Performance74.71%
/**
* @param {string} a
* @param {string} b
* @return {string}
*/
var addBinary = function(a, b) {
let maxLen = Math.max(a.length, b.length);
let carry = 0;
let res = '';
for (let i = 1; i <= maxLen; i++) {
const num1 = Number(a[a.length - i] || '0');
const num2 = Number(b[b.length - i] || '0');
const sum = num1 + num2 + carry;
res = (sum & 1 ? '1' : '0') + res;
carry = sum >= 2 ? 1 : 0;
}
return (carry ? '1' : '') + res;
};