#67 Add Binary

Posted mrdoghead

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了#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]
                

以上是关于#67 Add Binary的主要内容,如果未能解决你的问题,请参考以下文章

leetcode67. Add Binary

67. Add Binary

LeetCode----67. Add Binary(java)

67. Add Binary

67. Add Binary

leetcode67. Add Binary