您的位置:首页 > 编程语言 > Python开发

67. Add Binary [easy] (Python)

2016-06-18 17:29 555 查看

题目链接

https://leetcode.com/problems/add-binary/

题目原文

Given two binary strings, return their sum (also a binary string).

For example,

a = “11”

b = “1”

Return “100”.

题目翻译

给定两个二进制字符串,返回它们的和(也是二进制字符串)。

比如:a = “11”,b = “1”,返回 “100”。

思路方法

思路一

利用Python的进制转换函数,先将两个加数转成10进制,再把和转换成二进制返回即可。虽然速度还挺快的,但这么做忽略了可能的大整数相加的细节(因为Python帮你处理了)。

代码

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:]


思路二

从两个字符串的最低位开始,一位一位的进行二进制相加,并保存进位,最终可以得到两者的和的字符串。

代码

class Solution(object):
def addBinary(self, a, b):
"""
:type a: str
:type b: str
:rtype: str
"""
res = ''
i, j, plus = len(a)-1, len(b)-1, 0
while i>=0 or j>=0 or plus==1:
plus += int(a[i]) if i>= 0 else 0
plus += int(b[j]) if j>= 0 else 0
res = str(plus % 2) + res
i, j, plus = i-1, j-1, plus/2
return res


思路三

用递归实现,要注意,当两个加数都是1时要进位。

代码

class Solution(object):
def addBinary(self, a, b):
"""
:type a: str
:type b: str
:rtype: str
"""
if not a or not b:
return a if a else b
if a[-1] == '1' and b[-1] == '1':
return self.addBinary(self.addBinary(a[:-1], b[:-1]), '1') + '0'
elif a[-1] == '0' and b[-1] == '0':
return self.addBinary(a[:-1], b[:-1]) + '0'
else:
return self.addBinary(a[:-1], b[:-1]) + '1'


PS: 新手刷LeetCode,新手写博客,写错了或者写的不清楚还请帮忙指出,谢谢!

转载请注明:/article/11857873.html
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: