Created
September 6, 2018 21:32
-
-
Save yokolet/677ea98c649439566dcaffc744b48b7f to your computer and use it in GitHub Desktop.
Add Binary Strings
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
| """ | |
| Description: | |
| 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: | |
| Input: a = "1010", b = "1011" | |
| Output: "10101" | |
| """ | |
| # much faster using built-in function | |
| def addBinary(a, b): | |
| """ | |
| :type a: str | |
| :type b: str | |
| :rtype: str | |
| """ | |
| return '{:b}'.format(int(a, 2) + int(b, 2)) | |
| # slower but doesn't use Python specific built-in function | |
| def addBinary(a, b): | |
| """ | |
| :type a: str | |
| :type b: str | |
| :rtype: str | |
| """ | |
| result = '' | |
| idx_a, idx_b = len(a) - 1, len(b) - 1 | |
| carry = 0 | |
| while idx_a >= 0 or idx_b >= 0: | |
| d_a = 1 if idx_a >= 0 and a[idx_a] == '1' else 0 | |
| d_b = 1 if idx_b >= 0 and b[idx_b] == '1' else 0 | |
| tmp = carry + d_a + d_b | |
| carry, rem = tmp // 2, tmp % 2 | |
| result = str(rem) + result | |
| idx_a -= 1 | |
| idx_b -= 1 | |
| if carry == 1: | |
| result = '1' + result | |
| return result |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment