Leetcode: Add binary
The task is to add two binary numbers of various length. There is more than one possible solution. First, the basic solution which doesn’t use too many builtin Python functions works as follows: Reverse the strings containing the numbers. Then Iterate in a loop as long as we didn’t reach the end of both strings. Write the current position to a temporary variable if it’s still in the boundaries of the string. Then add a potential overflow and handle it if the sum of
a + b + overflow > 1. Finally, check for the overflow at the end and add a
1 and reverse the string again before returning it.
This can be solved much simpler with builtin Python functions.
First, the manual solution that can be transferred in any programming language.
Runtime: 67 ms, faster than 19.66% of Python3 online submissions for Add Binary.
Memory Usage: 13.9 MB, less than 25.21% of Python3 online submissions for Add Binary.
Now the solution that uses builtin Python functions.
The runtime of both approaches is about the same.