Python solution without using Bin()


  • -1
    M

    class Solution(object):
    def addBinary(self, a, b):
    """
    :type a: str
    :type b: str
    :rtype: str
    """
    s = str(int(a) + int(b))
    acc = 0
    for i in range(len(s)-1,-1,-1):
    if s[i] =='2' and acc == 0:
    s = s[:i]+'0'+s[i+1:]
    acc+=1
    elif s[i] =='2' and acc == 1:
    s = s[:i]+'1'+s[i+1:]
    elif s[i] =='1' and acc == 1:
    s = s[:i]+'0'+s[i+1:]
    elif s[i] =='0' and acc == 1:
    s = s[:i]+'1'+s[i+1:]
    acc-=1
    if i == 0 and acc == 1:
    s = '1'+ s
    return s


Log in to reply
 

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