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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21420447/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 22:48:23  来源:igfitidea点击:

Need help in adding binary numbers in python

pythonbinaryaddition

提问by user3246901

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, how should I create a code to figure out how to take carry over responses?

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

回答by Mostly Harmless

binand intare very useful here:

bin并且int在这里非常有用:

a = '001'
b = '011'

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

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

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

回答by mshsayem

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

如果您通过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'

回答by Algorithmatic

Here's an easy to understand version

这是一个易于理解的版本

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]

回答by SalchiPapa

This accepts an arbitrary number or arguments:

这接受任意数字或参数:

def bin_add(*args): return bin(sum(int(x, 2) for x in args))[2:]


>>> bin_add('1', '10', '100')
'111'

回答by Arturo Morales Rangel

you can use this function I did:

你可以使用我做的这个功能:

def addBinary(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) = 11

    sum = int(a, 2) + int(b, 2)

    if sum == 0: return "0"

    out = []

    while sum > 0:
        res = int(sum) % 2
        out.insert(0, str(res))
        sum = sum/2


    return ''.join(out)

回答by Sanya

Not an optimal solution but a working one without use of any inbuilt functions.

不是最佳解决方案,而是不使用任何内置功能的有效解决方案。

    # two approaches

    # first - binary to decimal conversion, add and then decimal to binary conversion
    # second - binary addition normally


    # binary addition - optimal approach
    # rules
    # 1 + 0 = 1
    # 1 + 1 = 0 (carry - 1)
    # 1 + 1 + 1(carry) = 1 (carry -1)

    aa = a
    bb = b
    len_a = len(aa) 
    len_b = len(bb) 

    min_len = min(len_a, len_b) 
    carry = 0
    arr = []

    while min_len > 0:
        last_digit_aa = int(aa[len(aa)-1]) 
        last_digit_bb = int(bb[len(bb)-1]) 

        add_digits = last_digit_aa + last_digit_bb + carry
        carry = 0
        if add_digits == 2:
            add_digits = 0
            carry = 1
        if add_digits == 3:
            add_digits = 1
            carry = 1

        arr.append(add_digits) # will rev this at the very end for output
        aa = aa[:-1]
        bb = bb[:-1]
        min_len -= 1

    a_len_after = len(aa)
    b_len_after = len(bb)

    if a_len_after > 0:
        while a_len_after > 0:
            while carry == 1:
                if len(aa) > 0:
                    sum_digit = int(aa[len(aa) - 1]) + carry
                    if sum_digit == 2:
                        sum_digit = 0
                        carry = 1
                        arr.append(sum_digit)
                        aa = aa[:-1]
                    else:
                        carry = 0
                        arr.append(sum_digit)
                        aa = aa[:-1]
                else:
                    arr.append(carry)
                    carry = 0

            if carry == 0 and len(aa) > 0:
                arr.append(aa[len(aa) - 1])
                aa = aa[:-1]
            a_len_after -= 1

    if b_len_after > 0:
        while b_len_after > 0:
            while carry == 1:
                if len(bb) > 0:
                    sum_digit = int(bb[len(bb) - 1]) + carry
                    if sum_digit == 2:
                        sum_digit = 0
                        carry = 1
                        arr.append(sum_digit)
                        bb = bb[:-1]
                    else:
                        carry = 0
                        arr.append(sum_digit)
                        bb = bb[:-1]
                else:
                    arr.append(carry)
                    carry = 0

            if carry == 0 and len(bb) > 0:
                arr.append(bb[len(bb) - 1])
                bb = bb[:-1]
            b_len_after -= 1

    if carry == 1:
        arr.append(carry)

    out_arr = reversed(arr)
    out_str = "".join(str(x) for x in out_arr)
    return out_str