Open fly0o0 opened 4 years ago
/**
* @param {string} a
* @param {string} b
* @return {string}
*/
var addBinary = function(a, b) {
let ans = ''
let carry = 0
for (let i = a.length - 1, j = b.length - 1; i >= 0 || j >= 0; i--, j--) {
let sum = carry
sum += i >= 0 ? parseInt(a[i], 10) : 0
sum += j >= 0 ? parseInt(b[j], 10) : 0
ans = sum % 2 + ans
carry = Math.floor(sum / 2)
}
if (carry == 1) {
ans = carry + ans
}
return ans
};