码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode#67 Add Binary

时间:2015-07-23 21:34:47      阅读:104      评论:0      收藏:0      [点我收藏+]

标签:

Problem Definition:

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

For example,
a = "11"
b = "1"
Return "100".

 

Solution: crack it in a Pythonista way:

1 def addBinary(a, b):
2     a=int(a,2)
3     b=int(b,2)
4     return bin(a+b)[2:]

 

Now let‘s recall something called full adder. And by simulating it, we get another solution, trivial though.

 1 def addBinary(self,a, b):
 2         if a==None or a==‘‘:
 3             return b
 4         if b==None or b==‘‘:
 5             return a
 6         ia,ib=len(a)-1,len(b)-1
 7         ba,bb,c=[0]*3
 8         s=‘‘
 9         while ia>=0 or ib>=0 or c==1:
10             ba=ord(a[ia])-ord(0) if ia>=0 else 0
11             bb=ord(b[ib])-ord(0) if ib>=0 else 0
12             ia-=1
13             ib-=1
14             r=ba^bb^c #xor
15             c=1 if ba+bb+c>=2 else 0
16             s+=str(r)
17         return s[::-1]

 

LeetCode#67 Add Binary

标签:

原文地址:http://www.cnblogs.com/acetseng/p/4671594.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!