[英]Need help in adding binary numbers in python
如果我有 2 个二进制形式的数字作为字符串,并且我想将它们相加,我将从最右边开始逐位进行。 所以 001 + 010 = 011 但是假设我必须做 001+001,我应该如何创建代码来弄清楚如何接管响应?
bin
和int
在这里非常有用:
a = '001'
b = '011'
c = bin(int(a,2) + int(b,2))
# 0b100
int
允许您在从字符串(在本例中为两个)转换时指定第一个参数的基数,而bin
将数字转换回二进制字符串。
这接受任意数字或参数:
>>> def bin_add(*bin_nums: str) -> str:
... return bin(sum(int(x, 2) for x in bin_nums))[2:]
...
>>> x = bin_add('1', '10', '100')
>>> x
'111'
>>> int(x, base = 2)
7
这是一个易于理解的版本
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]
如果您通过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'
你可以使用我做的这个功能:
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)
它是双向的
# as strings
a = "0b001"
b = "0b010"
c = bin(int(a, 2) + int(b, 2))
# as binary numbers
a = 0b001
b = 0b010
c = bin(a + b)
我添加 2 个二进制字符串的简单实现。
每个操作都包含一个内联解释。
首先将每个字符串零填充到相同的长度,然后反转两个字符串,以便操作将从 LSB(最低有效位)开始,然后使用 zip 方法同时循环遍历两个字符串。
然后进行简单的数学运算,计算 3 个 int 的 '1' 或 '0' 值,它们的总和为 0 到 3 的值,然后相应地修改结果字符串,如果 for 末尾的进位仍然有非零值循环,也将其添加到输出字符串中,然后反转输出字符串并返回它。
def add_binary(string_binary1, string_binary2):
# if empty strings, return empty string
if string_binary1 and string_binary2 is None:
return ""
result = ""
carry = 0
# get the length of the longest string
max_len = max(len(string_binary1), len(string_binary2))
# zero padding both of the strings, to get equal length, then reverse them both '011' --> '110'
string_binary1 = string_binary1.zfill(max_len)[::-1]
string_binary2 = string_binary2.zfill(max_len)[::-1]
# loop over both of the strings simultaneously
for digit1, digit2 in zip(string_binary1, string_binary2):
temp = int(digit1) + int(digit2) + carry
if temp > 1:
result = "".join(result + str(temp-2))
carry = 1
else:
result = "".join(result+str(temp))
carry = 0
# if carry is not zero at the end of the loop add it to the result string as well
result = "".join(result+str(carry)) if carry != 0 else result
# reverse and return the output binary string
return result[::-1]
def addBinary(self, A, B): min_len, res, carry, i, j = min(len(A), len(B)), '', 0, len(A) - 1, len(B) - 1 当 i>=0 和 j>=0 时:r = 进位 r += 1 如果 A[i] == '1' 否则 0 Z4B43B0AEE35624CD95B910189B3DC23Z =='1 else' + '1' 如果 r % 2 == 1 else '0') + res 进位 = 0 如果 r < 2 else 1 i -= 1 j -= 1
while i>=0:
r = carry
r += 1 if A[i] == '1' else 0
res = ('1' if r % 2 == 1 else '0') + res
carry = 0 if r < 2 else 1
i -= 1
while j>=0:
r = carry
r += 1 if B[j] == '1' else 0
res = ('1' if r % 2 == 1 else '0') + res
carry = 0 if r < 2 else 1
j -= 1
if carry == 1:
return '1' + res
return res
#添加两个二进制字符串而不使用'bin'内置 function
numb1 = input('enter the 1st binary number')
numb2 = input("enter the 2nd binary number")
list1 = []
carry = '0'
maxlen = max(len(numb1), len(numb2))
x = numb1.zfill(maxlen)
y = numb2.zfill(maxlen)
for j in range(maxlen-1,-1,-1):
d1 = x[j]
d2 = y[j]
if d1 == '0' and d2 =='0' and carry =='0':
list1.append('0')
carry = '0'
elif d1 == '1' and d2 =='1' and carry =='1':
list1.append('1')
carry = '1'
elif (d1 == '1' and d2 =='0' and carry =='0') or (d1 == '0' and d2 =='1' and
carry =='0') or (d1 == '0' and d2 =='0' and carry =='1'):
list1.append('1')
carry = '0'
elif d1 == '1' and d2 =='1' and carry =='0':
list1.append('0')
carry = '1'
else:
list1.append('0')
if carry == '1':
list1.append('1')
addition = ''.join(list1[::-1])
print(addition)
不是最佳解决方案,而是不使用任何内置功能的有效解决方案。
# 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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.