Skip to content

Latest commit

 

History

History
61 lines (50 loc) · 1.61 KB

67.md

File metadata and controls

61 lines (50 loc) · 1.61 KB

题目地址

https://leetcode-cn.com/problems/add-binary/

解答1

class Solution:
    def addBinary(self, a: str, b: str) -> str:
        """
            二进制求和(非最优解)

            给定两个二进制字符串,返回他们的和(用二进制表示)。
            输入为非空字符串且只包含数字 1 和 0。

            输入: a = "11", b = "1"
            输出: "100"
        """
        return str(bin(int(a, 2) + int(b, 2)))[2:]

解答2

class Solution:
    def addBinary(self, a: str, b: str) -> str:
        """
            二进制求和

            给定两个二进制字符串,返回他们的和(用二进制表示)。
            输入为非空字符串且只包含数字 1 和 0。

            输入: a = "11", b = "1"
            输出: "100"
        """
        if len(a) < len(b):
            a, b = b, a
        b, k, m, total = "0" * (len(a) - len(b)) + b, len(a) - 1, 0, ["0", ] * len(a)

        while k >= 0:
            m, n = divmod(ord(a[k]) - ord("0") + ord(b[k]) - ord("0") + m, 2)
            total[k] = str(n)
            k -= 1
        if m:
            total.insert(0, str(m))
        return "".join(total)

解答3

class Solution:
    def addBinary(self, a: str, b: str) -> str:
        """
            二进制求和(非最优解)

            给定两个二进制字符串,返回他们的和(用二进制表示)。
            输入为非空字符串且只包含数字 1 和 0。

            输入: a = "11", b = "1"
            输出: "100"
        """
        return format(int(a, 2) + int(b, 2), 'b')