简繁EN

LeetCodeNo. 037

[LeetCode with Python] 67. Add Binary

Contents

Problem

Problem page: https://leetcode.com/problems/add-binary/
Topics: Math, String
Difficulty: Easy
Similar problems: (M) Add Two Numbers, (M) Multiply Strings, (E) Plus One

Given two binary strings, return their sum (also a binary string).

For example,
a = "11"
b = "1"
Return "100".


Analysis

I use strings to simulate binary integer addition. I wrote a more general algorithm, so I can just change self.radix to make the code add octal integers, decimal integers, and so on.
But to make the addition easier to handle and keep the code short, I padded the two addend arrays with leading zeros. Otherwise I'd have to handle 3 cases separately: a is longer than b, b is longer than a, or a and b are the same length. The code could get a bit tedious.

(Since I'm using Python here, I went with the intuitive way of writing it and just added the strings together. But for efficiency, I should allocate a character array with size=max(len(a), len(b))+1 up front and then simulate the addition in that array.


Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
class Solution:

def __init__(self):
self.radix = 2

# @param a, a string
# @param b, a string
# @return a string
def addBinary(self, a, b):

a_nums = [(ord(ch) - ord('0')) for ch in a]
b_nums = [(ord(ch) - ord('0')) for ch in b]
a_nums_size = len(a_nums)
b_nums_size = len(b_nums)
max_nums_size = max(a_nums_size, b_nums_size)
a_extend_nums = [0 for i in range(0, max_nums_size - a_nums_size)]
b_extend_nums = [0 for i in range(0, max_nums_size - b_nums_size)]
a_nums = a_extend_nums + a_nums
b_nums = b_extend_nums + b_nums
sum_nums = [0] * max_nums_size

carry = 0
for i in range(max_nums_size - 1, -1, -1):
sum = a_nums[i] + b_nums[i] + carry
sum_nums[i] = sum % self.radix
carry = sum / self.radix

sum_str = ("1" if 1 == carry else "")
for i in range(0, max_nums_size):
sum_str += chr(sum_nums[i] + ord('0'))

return sum_str

Article link: https://xnerv.wang/en/leetcode-add-binary/