需要帮助在python中添加二进制数

use*_*901 12 python binary addition

如果我有二进制形式的2个数字作为字符串,并且我想添加它们,我将从最右端开始逐位数字.所以001 + 010 = 011但是假设我必须做001 + 001,我应该如何创建一个代码来弄清楚如何进行转移响应?

小智 34

bin并且int是非常有用的位置:

a = '001'
b = '011'

c = bin(int(a,2) + int(b,2))
# 0b100
Run Code Online (Sandbox Code Playgroud)

int允许您指定从字符串转换时第一个参数的基数(在本例中为2),bin并将数字转换回二进制字符串.


Sal*_*apa 8

这接受任意数量或参数:

def bin_add(*args): return bin(sum(int(x, 2) for x in args))[2:]
Run Code Online (Sandbox Code Playgroud)
>>> bin_add('1', '10', '100')
'111'
Run Code Online (Sandbox Code Playgroud)


msh*_*yem 5

int如果您通过(如其他答案所示)解析字符串,则可以很简单。这是幼儿园-学校-数学的方法:

>>> def add(x,y):
        maxlen = max(len(x), len(y))

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

        result = ''
        carry = 0

        for i in range(maxlen-1, -1, -1):
            r = carry
            r += 1 if x[i] == '1' else 0
            r += 1 if y[i] == '1' else 0

            # 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 == 1 else '0') + result
            carry = 0 if r < 2 else 1       

        if carry !=0 : result = '1' + result

        return result.zfill(maxlen)

>>> add('1','111')
'1000'
>>> add('111','111')
'1110'
>>> add('111','1000')
'1111'
Run Code Online (Sandbox Code Playgroud)


Alg*_*tic 5

这是一个易于理解的版本

def binAdd(s1, s2):
    if not s1 or not s2:
        return ''

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

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

    result  = ''
    carry   = 0

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

        i = i - 1;

    if carry>0:
        result = "%s%s" % (result, '1')
    return result[::-1]
Run Code Online (Sandbox Code Playgroud)