#67 Add Binary

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

The input strings are both non-empty and contains only characters 1 or 0.

Example 1:

Input: a = "11", b = "1"
Output: "100"

Example 2:

Input: a = "1010", b = "1011"
Output: "10101"

Solution1:

class Solution:
    def addBinary(self, a: str, b: str) -> str:
        if len(a) >= len(b):
            l = a[::-1]
            s = b[::-1]
        else:
            l = b[::-1]
            s = a[::-1]
        result = ""
        up = False
        for i in range(len(l)):
            if i < len(s):
                if not up:
                    if int(l[i]) + int(s[i]) == 2:
                        result += "0"
                        up = True
                    else:
                        result += str(int(l[i]) + int(s[i]))
                else:
                    if int(l[i]) + int(s[i]) == 2:
                        result += "1"
                    elif int(l[i]) + int(s[i]) == 1:
                        result += "0"
                    else:
                        result += "1"
                        up = False
            else:
                if not up:
                    result += l[i]
                else:
                    if l[i] == "1":
                        result += "0"
                    else:
                        result += "1"
                        up = False
        if up:
            result += "1"
        return result[::-1]
                
posted @ 2019-11-15 22:57  MrDoghead  阅读(123)  评论(0编辑  收藏  举报