1. 程式人生 > >領釦--二進位制求和--Python實現

領釦--二進位制求和--Python實現

給定兩個二進位制字串,返回他們的和(用二進位制表示)。

輸入為非空字串且只包含數字 1 和 0。

示例 1:

輸入: a = "11", b = "1"
輸出: "100"
示例 2:

輸入: a = "1010", b = "1011"
輸出: "10101"
'''
給定兩個二進位制字串,返回他們的和(用二進位制表示)。

輸入為非空字串且只包含數字 1 和 0。

示例 1:

輸入: a = "11", b = "1"
輸出: "100"
示例 2:

輸入: a = "1010", b = "1011"
輸出: "10101"
'''

class Solution:
    def addBinary(self, a, b):
        """
        :type a: str
        :type b: str
        :rtype: str
        """
        #return bin(int(a,2)+int(b,2))[2:]
        la, lb = len(a), len(b)
        i, j = la - 1, lb - 1
        cin = 0
        result = ''
        while (i >= 0) and (j >= 0):
            tmp = (cin + int(a[i]) + int(b[j])) % 2
            cin = (cin + int(a[i]) + int(b[j])) // 2
            result = str(tmp) + result
            i -= 1
            j -= 1
        if i < 0 and j >= 0:
            while j >= 0:
                tmp = (cin + int(b[j])) % 2
                cin = (cin + int(b[j])) // 2
                result = str(tmp) + result
                j -= 1
        elif i >= 0 and j < 0:
            while i >= 0:
                tmp = (cin + int(a[i])) % 2
                cin = (cin + int(a[i])) // 2
                result = str(tmp) + result
                i -= 1
        if cin == 1:
            result = '1' + result
        return result
object=Solution()
result=object.addBinary('101010','11101')
print(result)

GitHub原始碼:

https://github.com/tyutltf/Leecode