Simple python code and easy to understand


  • 1
    J
    class Solution:
        # @param a, a string
        # @param b, a string
        # @return a string
        def addBinary(self, a, b):
            add = False
            i = 0
            list = []
            while i < len(a) or i < len(b):
                temp = 0
                if i < len(a):
                    temp += int(a[-i - 1])
                if i < len(b):
                    temp += int(b[-i - 1])
                if add:
                    temp += 1
                    add = False
                if temp >= 2:
                    temp -= 2
                    add = True
                list.insert(0, str(temp))
                i += 1
            if add:
                list.insert(0, "1")
            return "".join(list)

  • 0
    D
    class Solution:
    # @param a, a string
    # @param b, a string
    # @return a string
    def addBinary(self, a, b):
        a = int(a,2)
        b = int(b,2)
        return bin(a+b)[2:]

  • 0
    H

    list.insert(0, "1") is O(n) operation. append and reverse the list finally is better


  • 0
    M

    cool ! make it a one liner

    class Solution:
    # @param a, a string
    # @param b, a string
    # @return a string
    def addBinary(self, a, b):
    return bin(int (a,2) + int (b,2))[2:]


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.