您的位置:首页 > 其它

leetcode -- Add Binary -- 简单要了解

2015-12-03 20:50 489 查看
https://leetcode.com/problems/add-binary/

知道二进制加法原理即可,这里只需要知道进位是除数,余数是结果就行。最后不要忽略reg里面的值

class Solution(object):
def addBinary(self, a, b):
"""
:type a: str
:type b: str
:rtype: str
"""
if not a:
return b
elif not b:
return a

tmp_str = ''.join(['0'] * abs(len(a) - len(b)))
if tmp_str:
if len(a) > len(b):
b = tmp_str + b
else:
a = tmp_str + a

reg = 0
res = ''
for i in xrange(len(a) - 1, -1, -1):
tmp = int(a[i]) + int(b[i]) + reg
mod, inc = tmp % 2, tmp / 2
res = str(mod) + res
#print (reg,tmp, mod, inc, res)
reg = inc
if reg != 0:
res = '1' + res
return res


看这个博客。整理的解题思路

http://c4fun.cn/blog/2014/03/20/leetcode-solution-02/
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: