Leetcode 算法题 67
题名:Add Binary
https://leetcode.com/problems/add-binary/#/description
题目描述:给定两个二进制字符串,返回他们的和(二进制字符串)
Given two binary strings, return their sum (also a binary string).
For example,
a = “11”
b = “1”
Return “100”.
解题思路:这道题的解答方法有很多,我的思路是把二进制字符串转化为十进制的整数,然后相加,再把结果转化为二进制的字符串
Python代码如下
class Solution(object):
def addBinary(self, a, b):
"""
:type a: str
:type b: str
:rtype: str
"""
dec_a = str2dec(a)
dec_b = str2dec(b)
dec_c = dec_a + dec_b
return dec2binStr(dec_c)
def str2dec(s):
sum = 0
for i in s:
sum = sum * 2 + int(i)
return sum
def dec2binStr(s):
ls = []
while s:
rem = s % 2
s = s / 2
ls.insert(0, str(rem))
if len(ls) != 0:
return ''.join(ls)
else:
return "0"