Given two binary strings, return their sum (also a binary string).
The input strings are both non-empty and contains only characters 1 or 0.
Example 1:
Input: a = “11”, b = “1” Output: “100” Example 2:
Input: a = “1010”, b = “1011” Output: “10101”
Solution:
The idea is to start from the end of string and add every bit.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
classSolution: defaddBinary(self, a: str, b: str) -> str: i, j = len(a)-1, len(b)-1 carry = 0 res = "" while i >= 0or j >= 0: x, y = 0, 0 x = 1if i >= 0and a[i] == '1'else0 y = 1if j >= 0and b[j] == '1'else0 res = str((x+y+carry)%2) + res carry = (x+y+carry)//2 i, j = i-1, j-1 if carry: res = str(carry%2) + res return res