|
| 1 | +class Solution: |
| 2 | + def addBinary(self, a, b): |
| 3 | + """ |
| 4 | + :type a: str |
| 5 | + :type b: str |
| 6 | + :rtype: str |
| 7 | + """ |
| 8 | + # Resultant string |
| 9 | + result = "" |
| 10 | + # Indices for a and b |
| 11 | + aLength = len(a) - 1 |
| 12 | + bLength = len(b) - 1 |
| 13 | + # Carry |
| 14 | + carry = 0 |
| 15 | + # Loop for all the characters in the strings |
| 16 | + while aLength >= 0 or bLength >= 0: |
| 17 | + # Sum of two bits |
| 18 | + totalSum = carry |
| 19 | + if aLength >= 0: |
| 20 | + totalSum += int(a[aLength]) |
| 21 | + aLength -= 1 |
| 22 | + if bLength >= 0: |
| 23 | + totalSum += int(b[bLength]) |
| 24 | + bLength -= 1 |
| 25 | + # Add the bit to te result |
| 26 | + result = str(totalSum % 2) + result |
| 27 | + # Modify carry |
| 28 | + carry = totalSum // 2 |
| 29 | + # Final check if carry exists |
| 30 | + if carry > 0: |
| 31 | + result = str(1) + result |
| 32 | + return result |
0 commit comments