-
-
Save humpydonkey/474122dfcf4e4f5bb3c2300940f6053f to your computer and use it in GitHub Desktop.
Saved from https://leetcode.com/problems/add-binary/
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Solution: | |
def addBinary(self, a: str, b: str) -> str: | |
res = [] | |
len_a = len(a) | |
len_b = len(b) | |
i = 0 | |
carry = 0 | |
while i < len_a or i < len_b: | |
sum = carry | |
if i < len_a: | |
sum += int(a[len_a-1-i]) | |
if i < len_b: | |
sum += int(b[len_b-1-i]) | |
remainder = int(sum % 2) | |
res.append(str(remainder)) | |
carry = floor(sum / 2) | |
i += 1 | |
if carry: | |
res.append("1") | |
return ''.join(res[::-1]) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment