67.Add Binary

 

 

class Solution:
    def addBinary(self, a: str, b: str) -> str:
        n = len(a) if len(a) > len(b) else len(b)
        a = a[::-1]
        b = b[::-1]
        tmp = 0
        ans = ""
        for i in range(n):
            if i > len(b) -1:
                if int(a[i]) + tmp == 2:
                    tmp = 1
                    ans += "0"
                else:
                    ans += str(int(a[i]) + tmp)
                    tmp = 0
            elif i > len(a) -1 :
                if int(b[i]) + tmp == 2:
                    tmp = 1
                    ans += "0"
                else:
                    ans += str(int(b[i]) + tmp)
                    tmp = 0
            else:
                if int(a[i]) + int(b[i]) + tmp == 2:
                    tmp = 1
                    ans += "0"
                elif int(a[i]) + int(b[i]) + tmp == 3:
                    tmp = 1
                    ans += "1"
                else:
                    ans += str(int(a[i]) + int(b[i]) + tmp)
                    tmp = 0
        if tmp == 1:
            ans += "1"
        return ans[::-1]

 

posted @ 2020-05-09 15:12  星海寻梦233  阅读(104)  评论(0编辑  收藏  举报