Need help adding python numbers in python

If I have 2 numbers in binary form as a string, and I want to add them, I will make it digit by digit, from the very end. So 001 + 010 = 011 But suppose I need to do 001 + 001, how do I create code to figure out how to accept portable answers?

+7
python binary addition
source share
4 answers

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 which base the first argument is when converting from a string (in this case, two), and bin converts the number back to a binary string.

+21
source share

This takes 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' 
+4
source share

It can be simple if you parse strings into int (shown in another answer). Here is the school path:

 >>> 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' 
+2
source share

The version is easy to understand.

 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] 
+2
source share

All Articles