Given two binary strings, return their sum (also a binary string).
The input strings are both non-empty and contains only characters 1
or 0
.
Example 1:
Input: a = "11", b = "1"
Output: "100"
Example 2:
Input: a = "1010", b = "1011"
Output: "10101"
LeetCode:链接
从最低位加到最高位,当前位相加结果是%2,进位是/2,记得处理每一次的进位和最后一次的进位,最后输出字符。
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))):
val = carry
if i < len(a):
val += int(a[-(i+1)])
if i < len(b):
val += int(b[-(i+1)])
carry, val = val // 2, val % 2
result = str(val) + result
if carry:
result = str(carry) + result
return result