- using binary addition i start adding from the least significant bit at the endof the string.
- carry variable stores overload from addition of bits in binary and adds it to the sum of the nexts bits while the loop continues.
- remainder of bits is added to the end of a result array which is returned as a string
-
Time complexity:O(Max(A,B))
-
Space complexity:O(Max(A,B))
function addBinary(a: string, b: string): string {
let i = a.length - 1;
let j = b.length - 1;
let carry = 0;
let result = [];
while (i >= 0 || j >= 0 || carry) {
let sum = carry;
if (i >= 0) sum += Number(a[i--]);
if (j >= 0) sum += Number(b[j--]);
result.unshift(sum % 2);
carry = Math.floor(sum / 2);
}
return result.join("");
}