您的位置:首页 > 其它

LeetCode#67 Add Binary

2015-07-23 20:15 330 查看
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:

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


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

def addBinary(self,a, b):
if a==None or a=='':
return b
if b==None or b=='':
return a
ia,ib=len(a)-1,len(b)-1
ba,bb,c=[0]*3
s=''
while ia>=0 or ib>=0 or c==1:
ba=ord(a[ia])-ord('0') if ia>=0 else 0
bb=ord(b[ib])-ord('0') if ib>=0 else 0
ia-=1
ib-=1
r=ba^bb^c #xor
c=1 if ba+bb+c>=2 else 0
s+=str(r)
return s[::-1]
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: