给定两个二进制字符串,返回他们的和(用二进制表示)。
输入为非空字符串且只包含数字 1
和 0
。
示例 1:
输入: a = "11", b = "1" 输出: "100"
示例 2:
输入: a = "1010", b = "1011" 输出: "10101"
第一种思路:
Python大法好。 [2 : ]是为了去掉最前面的0b。
class Solution(object):
def addBinary(self, a, b):
"""
:type a: str
:type b: str
:rtype: str
"""
return bin(int(a,2) + int(b,2))[2:]
第二种思路:
先让a 做长字符串,b做短字符串,
把a, b倒序转换成int 的list,然后从头开始加,
加完之后对a进行操作,每个元素如果大于2 就进位,记得进位的时候也要调整la的值,
最后返回的是字符串形式。
class Solution(object):
def addBinary(self, a, b):
"""
:type a: str
:type b: str
:rtype: str
"""
a = list(a)
for index, item in enumerate(a):
a[index] = int(item)
b = list(b)
for index, item in enumerate(b):
b[index] = int(item)
la = len(a)
lb = len(b)
if la < lb:
a,b = b, a
la,lb = lb, la
a = a[::-1]
b = b[::-1]
for i in range(0, lb):
a[i] += b[i]
# print a
for i in range(0, la):
while a[i] >= 2:
a[i] -= 2
if i!=la-1:
a[i + 1] += 1
else:
a.append(1)
la += 1
# print a
res = ""
for item in a[::-1]:
res += str(item)
return res