题目:
给定两个二进制字符串,返回他们的和(用二进制表示)。
输入为非空字符串且只包含数字 1 和 0。
示例 1:
输入: a = "11", b = "1"
输出: "100"
示例 2:
输入: a = "1010", b = "1011"
输出: "10101"
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/add-binary
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
思路:
先对更短的字符串补0;
遍历字符串相加,记录有没有进位
最后还有进位,加在最前面。
代码:
class Solution(object):
def addBinary(self, a, b):
"""
:type a: str
:type b: str
:rtype: str
"""
res=""
m=len(a)-1
n=len(b)-1
tmp=0
if m-n>0:
i=m
b='0'*(m-n)+b
else:
i=n
a='0'*(n-m)+a
for j in range(i,-1,-1):
aj=int(a[j])
bj=int(b[j])
tmp=aj+bj+tmp
if tmp>=2:
res=str(tmp-2)+res
tmp=1
else:
res=str(tmp)+res
tmp=0
if tmp>0:
res=str(tmp)+res
return res