【leetcode】Add Binary

题目简述:

Given two binary strings, return their sum (also a binary string).

For example,
a = "11"
b = "1"
Return "100".

解题思路:

class Solution:
    # @param a, a string
    # @param b, a string
    # @return a string
    def addBinary(self, a, b):
        la = len(a) - 1
        lb = len(b) - 1
        f = 0
        res = []
        while la >= 0 or lb >= 0:
            A = 0
            B = 0
            if la >= 0:
                A = int(a[la])
                la -= 1
            if lb >= 0:
                B = int(b[lb])
                lb -= 1
            if A + B +f >= 2:
                res.append(str(A + B +f - 2))
                f = 1
            else:
                res.append(str(A + B +f ))
                f = 0
        if f ==1:
            res.append('1')
        res.reverse()
        return "".join(res)

你可能感兴趣的:(LeetCode)