标签:
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]
标签:
原文地址:http://www.cnblogs.com/acetseng/p/4671594.html