Leetcode #67: Add Binary
I'm a little confused by this one to be honest. The Leetcode solutions section for this problem is littered with complicated solutions which makes me question whether my solution is wrong somehow, but it's very simple, Pythonic, and passes all the tests, so idfk.
Solving the problem
The steps, as I see them, are pretty straightforward.
Convert each binary string to an integer.
Add the integers together.
Convert the integer sum back into a binary string.
The solution looks like this.
def add_binary(a, b):
return format(int(a, base=2) + int(b, base=2), "b")
Starting inside format()
, a
and b
are converted to integers using the int()
built-in function. If the first positional argument of the function is a string, the function takes an optional keyword argument base
that designates how the positional argument should be interpreted. int("11", base=2)
would return 3
. int("11", base=10)
would return 11
. Since we want the integer form of a binary string a
(base 2), we just do int(a, base=2)
, do the same for b
, and add them together.
All that's left to do is convert the resulting integer back to a binary string. The format()
built-in provides a concise way to do this by letting us convert a value into a specified format. Binary is represented by "b"
so we set the second argument in format()
to "b"
.
Hopefully that clarifies the above solution. If I find out that this solution is dangerously bad, I'll come back and apologize.