Advertisement
DeepRest

Add Binary

Jan 10th, 2022
79
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.76 KB | None | 0 0
  1. '''
  2. Full Adder Logic:
  3. S = Cin ^ X ^ Y
  4. Cout = Cin&X + X&Y + Y&Cin
  5. Final Result = Cout.S(final)
  6. Initial c = 0, s = 0
  7. '''
  8. class Solution:
  9.     def addBinary(self, a: str, b: str) -> str:
  10.         cin = 0
  11.         res = []
  12.         m, n = len(a), len(b)
  13.         for i in range(max(m, n)):
  14.             s = cin
  15.             cout = 0
  16.             if i < m:
  17.                 x = int(a[-i-1])
  18.                 s ^= x
  19.                 cout |= cin & x
  20.             if i < n:
  21.                 y = int(b[-i-1])
  22.                 s ^= y
  23.                 cout |= cin & y
  24.             if i < m and i < n:
  25.                 cout |= x & y
  26.             res.append(str(s))
  27.             cin = cout
  28.         if cin:
  29.             res.append(str(cin))
  30.         return ''.join(res[::-1])
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement