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

[Leetcode]@python 67. Add Binary

2016-01-12 16:08 204 查看
题目链接:https://leetcode.com/problems/add-binary/

题目大意:给定两个二进制字符串,返回它们的和

解题思路:模拟二进制竖式加法

class Solution(object):
def addBinary(self, a, b):
"""
:type a: str
:type b: str
:rtype: str
"""
len_a = len(a)
len_b = len(b)
if len_a == 0:
return b
if len_b == 0:
return a
ans = ""
carry = 0
while len_a > 0 and len_b:
tmp = int(a[len_a - 1]) + int(b[len_b - 1]) + carry
carry = tmp // 2
tmp %= 2
ans += str(tmp)
len_a -= 1
len_b -= 1
if len_a == 0:
while len_b > 0:
tmp = int(b[len_b - 1]) + carry
carry = tmp // 2
tmp %= 2
ans += str(tmp)
len_b -= 1
if len_b == 0:
while len_a > 0:
tmp = int(a[len_a - 1]) + carry
carry = tmp // 2
tmp %= 2
ans += str(tmp)
len_a -= 1
if carry == 1:
ans += str(carry)
ans = ans[::-1]
return ans


View Code
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: