Python学習——leetcode(Add Binary)

986 ワード

class Solution:
    # @param a, a string
    # @param b, a string
    # @return a string
    def addBinary(self, a, b):
		c=[]
		if a:
			i,j=len(a)-1,len(b)-1
			anum=list(a)
			bnum=list(b)
<span style="white-space:pre">			</span>#    
			temp=0
			while i>=0 and j>=0:
				num=int(a[i])+int(b[j])+temp
				if num>=2:
					temp=1
					c.insert(0,str(num-2))
				else:
					temp=0
					c.insert(0,str(num))
				i-=1
				j-=1
			while i>=0:
				num=int(a[i])+temp
				if num>=2:
					temp=1
					c.insert(0,str(num-2))
				else:
					temp=0
					c.insert(0,str(num))
				i-=1
			while j>=0:
				num=int(b[j])+temp
				if num>=2:
					temp=1
					c.insert(0,str(num-2))
				else:
					temp=0
					c.insert(0,str(num))
				j-=1
			while temp>0:
				c.insert(0,str(temp))
				temp=0
			return ''.join(c)
		else:
			if b:
				return b
			else:
				return ''