Given two binary strings a and b, return their sum as a binary string.
Add like on paper: walk both strings from the right, sum the two digits and the carry, write sum % 2 and carry sum >> 1.
1function addBinary(a: string, b: string): string {2let i = a.length - 1, j = b.length - 1, carry = 0, out = "";3while (i >= 0 || j >= 0 || carry) {4const sum = (i >= 0 ? +a[i--] : 0) + (j >= 0 ? +b[j--] : 0) + carry;5out = (sum % 2) + out;6carry = sum >> 1;7}8return out;9}
Start at the rightmost digit of each string.
Space: play/pause · ←/→: step