LeetCode- 二进制求和
题目描述
给你两个二进制字符串,返回它们的和(用二进制表示)。
输入为 非空 字符串且只包含数字 1 和 0。
示例一:
示例二:
说明:
思路说明
第一想法是一种很简单的思路,将字符串反转,转换成list的格式,然后两个List对应位依次相加,满二进一,最后再将结果返回来,再输出。后面懂了好的方法会持续更新,欢迎大家批评指正。
代码实现
class Solution(object):
def bi_add(self, a_list, ll):
i = 0
jinwei = 0
while i < len(a_list) and i < len(ll):
temp = a_list[i] + ll[i] + jinwei
jinwei = temp/2
a_list[i] = temp % 2
i += 1
while i < len(a_list):
temp = jinwei + a_list[i]
jinwei = temp/2
a_list[i] = temp % 2
i += 1
if jinwei:
a_list.append(1)
b = ''.join(str(k) for k in reversed(a_list))
return b
def addBinary(self, a, b):
"""
:type a: str
:type b: str
:rtype: str
"""
a_list = [int(i) for i in reversed(a)]
b_list = [int(i) for i in reversed(b)]
len1 = len(a_list)
len2 = len(b_list)
if len1 >= len2:
c = self.bi_add(a_list, b_list)
else:
c = self.bi_add(b_list, a_list)
return c
题目来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/add-binary/