67. Add Binary
https://leetcode.com/problems/add-binary/
js
/**
* @param {string} a
* @param {string} b
* @return {string}
*/
var addBinary = function(a, b) {
a = a.split('').reverse()
b = b.split('').reverse()
var carry = 0
var result = []
var len = Math.max(a.length, b.length)
for (let i = 0; i < len; i++) {
let sum = (+a[i] || 0) + (+b[i] || 0) + carry
result.push(sum % 2)
carry = sum / 2 >> 0
}
if (carry) {
result.push(carry)
}
return result.reverse().join('')
}
py
class Solution(object):
def addBinary(self, a, b):
"""
:type a: str
:type b: str
:rtype: str
"""
result = []
carry = 0
for i in range(max(len(a), len(b))):
val1 = int(a[-i - 1]) if i < len(a) else 0
val2 = int(b[-i - 1]) if i < len(b) else 0
val = val1 + val2 + carry
result.append(str(val % 2))
carry = val // 2
if carry > 0:
result.append(str(carry))
return ''.join(result[::-1])