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 | class Solution: |
Article link: https://xnerv.wang/en/leetcode-add-binary/
