Leetcode練習(Python):數學類:第67題:二進制求和:給你兩個二進制字符串,返回它們的和(用二進制表示)。 輸入為 非空 字符串且只包含數字 1 和 0。


題目:
二進制求和:給你兩個二進制字符串,返回它們的和(用二進制表示)。  輸入為 非空 字符串且只包含數字 1 和 0。

提示:

每個字符串僅由字符 '0' 或 '1' 組成。
1 <= a.length, b.length <= 10^4
字符串如果不是 "0" ,就都不含前導零。

思路:

模擬二進制運算的過程。

程序:

class Solution:
    def addBinary(self, a: str, b: str) -> str:
        length1 = len(a)
        length2 = len(b)
        if length1 < 1 or length1 > 10 ** 4:
            return 
        if length2 < 1 or length2 > 10 ** 4:
            return
        result = ""
        carry_out = 0
        index1 = length1 - 1
        index2 = length2 - 1
        while index1 >= 0 or index2 >= 0 or carry_out == 1:
            if index1 >= 0:
                auxiliary1 = int(a[index1])
            else:
                auxiliary1 = 0
            if index2 >= 0:
                auxiliary2 = int(b[index2])
            else:
                auxiliary2 = 0
            carry_out, auxiliary3 = divmod(auxiliary1 + auxiliary2 + carry_out, 2)
            result = str(auxiliary3) + result
            index1 -= 1
            index2 -= 1
        return result


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM