Advertisement
smj007

Untitled

Mar 16th, 2025
183
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.62 KB | None | 0 0
  1. class Solution:
  2.     def addBinary(self, a: str, b: str) -> str:
  3.        
  4.         """
  5.        1 1 0
  6.        1 0 1
  7.  
  8.        0 + 0 = 0
  9.        1 + 1 = 10
  10.        1 + 1 + 1 = 11
  11.        """
  12.        
  13.         # add zeros at the beginning of the string
  14.         n = max(len(a), len(b))
  15.         a = a.zfill(n)
  16.         b = b.zfill(n)
  17.  
  18.         result = ""
  19.  
  20.         carry = 0
  21.         for i in range(n-1, -1, -1):
  22.             total = carry + int(a[i]) + int(b[i])
  23.             result = str(total%2) + result
  24.             carry = total//2
  25.  
  26.         if carry>0:
  27.             result = str(carry) + result
  28.  
  29.         return result
  30.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement