Leetcode - binary sum (67)

Description Title: Given two binary string, and return to their (expressed in binary). And a non-empty input string contains only numeric  1 and  0.

A thought: Use built-in functions python

1 class Solution:
2     def addBinary(self, a: str, b: str) -> str:
3         return '{0:b}'.format(int(a,2)+int(b,2))    #int(x, base=10)

About some of the usage format of reference https://www.cnblogs.com/benric/p/4965224.html

Thinking two: Set flag indicating whether a carry.

. 1  class Solution:
 2      DEF addBinary (Self, A: STR, B: STR) -> STR:
 . 3          In Flag = 0
 . 4          n-= max (len (A), len (B))
 . 5          A, B = a.zfill ( n-), b.zfill (n-)     # zfill from the left end is padded with zeros until a string of n- 
. 6          ANS = '' 
. 7          for I in Range (. 1, len (A) + 1'd ):
 . 8              IF A [-i ] == ' . 1 ' :
 . 9                  In Flag. 1 = +
 10              IF B [-i] == ' . 1 ' :
. 11                  In Flag +. 1 =
 12 is              IF In Flag == 2%. 1:     # In Flag indicates a carry digit 
13 is                  ANS = + ' . 1 ' 
14              the else : 
 15                  ANS + = ' 0 ' 
16              In Flag // = 2
 . 17          IF In Flag ==. 1 :
 18 is              ANS = + ' . 1 ' 
. 19          return ANS [-1 :: -. 1]     # reverse output

Three ideas : no addition calculation is calculated in bits.

           As shown, not the carry bit adder corresponding to simple XOR operation (when the value of a and b are not simultaneously 1)

 

     As shown, the carry generated by calculation. For example one, i.e., the green box before adding the carry generated by the blue box is added to the corresponding bit

 

 Loop will not carry into the adder adding the result generated, until a carry is not generated so far (i.e., when carry = 0)

. 1  class Solution:
 2      DEF addBinary (Self, A: STR, B: STR) -> STR:
 . 3          X, Y = int (A, 2), int (B, 2 )
 . 4          the while Y:
 . 5              ANS = X ^ Y     # XOR operation 
. 6              with Carry = (X & Y). 1 <<     # phase and left 
. 7              X, Y = ANS, with Carry
 . 8          return bin (X) [2:]     # because the binary outputs are 0bxxxx

 

Guess you like

Origin www.cnblogs.com/shawn-young/p/12601583.html