Add Binary

Problem: Add Binary

In this problem, we can just start adding from the end of the strings to the heads. Don't forget to deal with different lengths and carries.

Code in Python:

class Solution(object):
    def addBinary(self, a, b):
        """
        :type a: str
        :type b: str
        :rtype: str
        """
        pa, pb, carry, res = len(a)-1, len(b)-1, False, ""
        while pa + pb != -2:
            ca = a[pa] if pa >= 0 else "0"
            cb = b[pb] if pb >= 0 else "0"

            if ca == "1" and cb == "1":
                if carry: res = "1" + res
                else: res, carry = "0" + res, True
            elif (ca == "0" and cb == "1") or (ca == "1" and cb == "0"):
                if carry: res = "0" + res
                else: res = "1" + res
            else:
                if carry: res, carry = "1" + res, False
                else: res = "0" + res

            if pa >= 0: pa -= 1
            if pb >= 0: pb -= 1
        return "1" + res if carry else res

results matching ""

    No results matching ""