67. Add Binary
- Total Accepted: 108940
- Total Submissions: 367877
- Difficulty: Easy
- Contributors: Admin
Given two binary strings, return their sum (also a binary string).
For example,
a = "11"
b = "1"
Return "100"
.
Code
class Solution(object): def addBinary(self, a, b): """ :type a: str :type b: str :rtype: str """ if len(b) > len(a): a, b = b, a b = '0' * (len(a)-len(b)) + b carry = 0 res = ['0'] * (len(a)) for idx, (i,j) in enumerate(zip(a[::-1], b[::-1])): tmp = i + j + carry if tmp < 2: res[-idx-1] = str(tmp) else: res[-idx-1] = str(tmp % 2) carry = 1 # result cannot be longer than len(a)+1 if carry: return str(carry) + ''.join(res) else: return ''.join(res)
Idea
From right to left, add each position.