LeetCode 67 Add Binary (Python)

Posted by 小明MaxMing on July 19, 2020

题目

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.

解题思路

模拟两个数的加法,维护一个进位

代码

class Solution:
    def addBinary(self, a: str, b: str) -> str:
        def add(x, y, carry):
            s = x + y + carry        
            return (s // 2, s % 2)
    
        ml = max(len(a), len(b))
        res = ''
        carry = 0 
        a = a.rjust(ml, '0')
        b = b.rjust(ml, '0')
        for i in range(ml-1, -1, -1):         
            carry, s = add(int(a[i]), int(b[i]), int(carry))
            res = str(s) + res
        return '1' + res if carry else res

视频讲解 YouTube<--欢迎点击订阅

视频讲解 bilibili<--欢迎点击订阅