算法练习 Leetcode 力扣 67. Add Binary 解法

add strings基本一样。

关键点:
从右边开始加
把长的input作为第一个,给最左边加0用来进位(如果需要的话),最后看要不要去掉
python里面要用ord,chr 来做char/ascii转换

python解法

class Solution(object):
    def addBinary(self, a, b):
        """
        :type a: str
        :type b: str
        :rtype: str
        """
        if a is None or len(a) == 0:
            return b
        if b is None or len(b) == 0:
            return a
        if len(a) < len(b):
            return self.addBinary(b, a)
        n1 = ['0'] + [c for c in a]
        n2 = [c for c in b]
        
        i = len(n1) - 1
        j = len(n2) - 1
        while i >= 0:
            if j >= 0:
                n1[i] = chr(ord(n1[i]) + ord(n2[j]) - ord('0'))
            if n1[i] > '1':
                n1[i] = chr(ord(n1[i]) - 2)
                n1[i - 1] = chr(ord(n1[i - 1]) + 1)
            i -= 1
            j -= 1
        ans = ''.join(n1)
        if ans[0] == '0':
            return ans[1:]
        return ans

Leave a Comment

Your email address will not be published.