题目:
给定两个二进制字符串,返回他们的和(用二进制表示)。
输入为非空字符串且只包含数字 1 和 0。
示例 1:
输入: a = "11", b = "1"
输出: "100"
示例 2:
输入: a = "1010", b = "1011"
输出: "10101"
链接:https://leetcode-cn.com/problems/add-binary
思路:
1、先把两个数转化成十进制,相加后再转成二进制
Python代码:
class Solution(object):
def addBinary(self, a, b):
"""
:type a: str
:type b: str
:rtype: str
"""
sum_a = 0
for i in a:
sum_a = sum_a*2 + int(i)
sum_b = 0
for j in b:
sum_b = sum_b*2 + int(j)
sum = sum_a + sum_b
if sum==0:
return "0"
ls = []
while sum:
ls.append(str(sum%2))
sum /= 2
return ''.join(ls[::-1])