Skip to content Skip to sidebar Skip to footer

Need Help In Adding Binary Numbers In Python

If I have 2 numbers in binary form as a string, and I want to add them I will do it digit by digit, from the right most end. So 001 + 010 = 011 But suppose I have to do 001+001, ho

Solution 1:

bin and int are very useful here:

a = '001'b = '011'c = bin(int(a,2) + int(b,2))
# 0b100

int allows you to specify what base the first argument is in when converting from a string (in this case two), and bin converts a number back to a binary string.

Solution 2:

This accepts an arbitrary number or arguments:

>>>defbin_add(*bin_nums: str) -> str: ...returnbin(sum(int(x, 2) for x in bin_nums))[2:]...>>>x = bin_add('1', '10', '100')>>>x
'111'
>>>int(x, base = 2)
7

Solution 3:

Here's an easy to understand version

def binAdd(s1, s2):
    ifnot s1 ornot s2:
        return''

    maxlen = max(len(s1), len(s2))

    s1 = s1.zfill(maxlen)
    s2 = s2.zfill(maxlen)

    result  = ''
    carry   = 0

    i = maxlen - 1while(i >= 0):
        s = int(s1[i]) + int(s2[i])
        if s == 2: #1+1if carry == 0:
                carry = 1
                result = "%s%s" % (result, '0')
            else:
                result = "%s%s" % (result, '1')
        elif s == 1: # 1+0if carry == 1:
                result = "%s%s" % (result, '0')
            else:
                result = "%s%s" % (result, '1')
        else: # 0+0if carry == 1:
                result = "%s%s" % (result, '1')
                carry = 0else:
                result = "%s%s" % (result, '0') 

        i = i - 1;

    if carry>0:
        result = "%s%s" % (result, '1')
    return result[::-1]

Solution 4:

Can be simple if you parse the strings by int (shown in the other answer). Here is a kindergarten-school-math way:

>>> defadd(x,y):
        maxlen = max(len(x), len(y))

        #Normalize lengths
        x = x.zfill(maxlen)
        y = y.zfill(maxlen)

        result = ''
        carry = 0for i inrange(maxlen-1, -1, -1):
            r = carry
            r += 1if x[i] == '1'else0
            r += 1if y[i] == '1'else0# r can be 0,1,2,3 (carry + x[i] + y[i])# and among these, for r==1 and r==3 you will have result bit = 1# for r==2 and r==3 you will have carry = 1

            result = ('1'if r % 2 == 1else'0') + result
            carry = 0if r < 2else1if carry !=0 : result = '1' + result

        return result.zfill(maxlen)

>>> add('1','111')
'1000'>>> add('111','111')
'1110'>>> add('111','1000')
'1111'

Solution 5:

you can use this function I did:

defaddBinary(self, a, b):
    """
    :type a: str
    :type b: str
    :rtype: str
    """#a = int('10110', 2) #(0*2** 0)+(1*2**1)+(1*2**2)+(0*2**3)+(1*2**4) = 22#b = int('1011', 2) #(1*2** 0)+(1*2**1)+(0*2**2)+(1*2**3) = 11sum = int(a, 2) + int(b, 2)

    ifsum == 0: return"0"

    out = []

    whilesum > 0:
        res = int(sum) % 2
        out.insert(0, str(res))
        sum = sum/2return''.join(out)

Post a Comment for "Need Help In Adding Binary Numbers In Python"